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
Sinan81/PSAT-master
fm_threed.m
.m
PSAT-master/psat-oct/psat/fm_threed.m
11,096
utf_8
a9f48ea419066334caf6e7e619ec2e0b
function varargout = fm_threed(varargin) % FM_THREED create GUI for network visualisations % % HDL = FM_THREED() % %Author: Federico Milano %Date: 21-Aug-2007 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings Theme Varout Path Fig File CPF OPF % check for data file if isempty(File.data) fm_disp('Set a data file for running sparse matrix visualisation.',2) return end % check for initial power flow solution if ~Settings.init fm_disp('Solve base case power flow...') Settings.show = 0; fm_set('lf') Settings.show = 1; if ~Settings.init, return, end end if nargin if ~ishandle(Fig.threed), return, end hdl1 = findobj(Fig.threed,'Tag','PopupMenu1'); hdl2 = findobj(Fig.threed,'Tag','PopupMenu2'); value1 = get(hdl1,'Value'); value2 = get(hdl2,'Value'); switch varargin{1} case 'update' hdl3 = findobj(Fig.threed,'Tag','MenuCaxis'); if value2 == 1 set(hdl3,'Enable','on') else set(hdl3,'Enable','off') end if (value2 == 6 || value2 == 7) && ~OPF.init fm_disp(['Run OPF before displaying Locational Marginal ' ... 'Prices'],2) set(hdl2,'Value',1) set(hdl3,'Enable','on') return end fm_simrep('DrawModel',value1,value2,0) case 'init' Varout.movie = getframe(findobj(Fig.threed,'Tag','Axes1')); hdl = findobj(Fig.threed,'Tag','Axes1'); togglecontrols(Fig.threed,'off') case 'newframe' fm_simrep('DrawModel',value1,value2,1) case 'finish' togglecontrols(Fig.threed,'on') case 'movie' if isempty(Varout.movie), return, end axes(findobj(Fig.threed,'Tag','Axes1')); xlabel('') %axes('Position',[0 0 1 1]) if Settings.init > 1 && ~CPF.init fps = round(length(Varout.movie)/(Settings.tf-Settings.t0)); if ~fps, fps = 12; end movie(Varout.movie,1,fps) else movie(Varout.movie) end case 'savemovie' if isempty(Varout.movie), return, end cd(Path.data) filedata = strrep(File.data,'@ ',''); filedata = strrep(filedata,'(mdl)','_mdl'); mov = VideoWriter(filedata); open(mov); writeVideo(mov, Varout.movie); close(mov); cd(Path.local) case 'openmovie' [filename, pathname] = uigetfile('*.avi', 'Pick an AVI-file'); if ~pathname, return, end cd(pathname) Varout.movie = aviread(filename); cd(Path.local) case 'setcaxis' switch get(gcbo,'Checked') case 'on' set(gcbo,'Checked','off') Varout.caxis = 0; case 'off' set(gcbo,'Checked','on') Varout.caxis = 1; end fm_simrep('DrawModel',value1,value2,0) case 'printfig' togglecontrols(Fig.threed,'off') cd(Path.data) filedata = strrep(File.data,'@ ',''); filedata = strrep(filedata,'(mdl)','_mdl'); print(Fig.threed,'-dpng',filedata) cd(Path.local) togglecontrols(Fig.threed,'on') end return end if ishandle(Fig.threed), figure(Fig.threed), return, end maps = {'jet';'hot';'gray';'bone';'copper';'pink'; 'hsv';'cool';'autumn';'spring';'winter';'summer'}; h0 = figure('Color',Theme.color01, ... 'Units', 'normalized', ... 'CreateFcn','Fig.threed = gcf;', ... 'DeleteFcn','Fig.threed = -1; rotate3d off', ... 'FileName','fm_threed', ... 'MenuBar','none', ... 'Name','Network Visualisation', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',sizefig(0.666,0.74), ... 'Resize','on', ... 'ToolBar','none'); % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed openmovie', ... 'Label', 'Open movie', ... 'Tag','OpenMovie', ... 'Accelerator','o'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed savemovie', ... 'Label', 'Save movie', ... 'Tag','SaveMovie', ... 'Accelerator','s'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed printfig', ... 'Label', 'Save frame', ... 'Tag','PrintFig', ... 'Accelerator','p'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Close', ... 'Tag','FileClose', ... 'Separator','on', ... 'Accelerator','q'); % Menu Edit h1 = uimenu('Parent',h0, ... 'Label','Edit', ... 'Tag','MenuEdit'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed update', ... 'Label', 'Update', ... 'Accelerator','u', ... 'Tag','MenuUpdate'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed movie', ... 'Label', 'Play movie', ... 'Accelerator','m', ... 'Tag','MenuPlay'); % Menu View h1 = uimenu('Parent',h0, ... 'Label','View', ... 'Tag','MenuView'); h2 = uimenu('Parent',h1, ... 'Callback','fm_threed setcaxis', ... 'Label', 'Use voltage limits', ... 'Accelerator','v', ... 'Tag','MenuCaxis'); if Varout.caxis set(h1,'Checked','on') else set(h1,'Checked','off') end h2 = uimenu('Parent',h1, ... 'Label', 'Transparency', ... 'Tag','MenuTransparency', ... 'Separator','on'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(1), Varout.alpha = 1;', ... 'Label','None', ... 'Tag','alpha1', ... 'Accelerator','0'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.9), Varout.alpha = 0.9;', ... 'Label','alpha = 0.9', ... 'Tag','alpha1', ... 'Accelerator','9'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.8), Varout.alpha = 0.8;', ... 'Label','alpha = 0.8', ... 'Tag','alpha1', ... 'Accelerator','8'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.7), Varout.alpha = 0.7;', ... 'Label','alpha = 0.7', ... 'Tag','alpha1', ... 'Accelerator','7'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.6), Varout.alpha = 0.6;', ... 'Label','alpha = 0.6', ... 'Tag','alpha1', ... 'Accelerator','6'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.5), Varout.alpha = 0.5;', ... 'Label','alpha = 0.5', ... 'Tag','alpha1', ... 'Accelerator','5'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.4), Varout.alpha = 0.4;', ... 'Label','alpha = 0.4', ... 'Tag','alpha1', ... 'Accelerator','4'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.3), Varout.alpha = 0.3;', ... 'Label','alpha = 0.3', ... 'Tag','alpha1', ... 'Accelerator','3'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.2), Varout.alpha = 0.2;', ... 'Label','alpha = 0.2', ... 'Tag','alpha1', ... 'Accelerator','2'); h3 = uimenu('Parent',h2, ... 'Callback','alpha(0.1), Varout.alpha = 0.1;', ... 'Label','alpha = 0.1', ... 'Tag','alpha1', ... 'Accelerator','1'); %fm_set colormap h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',Theme.color11, ... 'Position',[0.09 0.152 0.85 0.779], ... 'Tag','Axes1', ... 'XColor',[0 0 0], ... 'YColor',[0 0 0], ... 'ZColor',[0 0 0]); set(h0,'UserData',h1); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('threed_matlab'), ... 'BackgroundColor',Theme.color02, ... 'Units', 'normalized', ... 'Callback','fm_threed update', ... 'Position',[0.673 0.0185 0.06 0.08], ... 'TooltipString','Update', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('threed_movie'), ... 'BackgroundColor',Theme.color02, ... 'Units', 'normalized', ... 'Callback','fm_threed movie', ... 'Position',[0.673+0.0650 0.0185 0.06 0.08], ... 'TooltipString','Play Movie', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'BackgroundColor',Theme.color02, ... 'Units', 'normalized', ... 'Callback','close(gcf)', ... 'Position',[0.82 0.044 0.121 0.052], ... 'String','Close', ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback','String = get(gcbo,''String''); eval([''colormap '',String{get(gcbo,''Value'')}]);', ... 'BackgroundColor',Theme.color04, ... 'Position',[0.488 0.041 0.157 0.056], ... 'String',maps, ... 'Style','popupmenu', ... 'Tag','PopupMenu1', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback','fm_threed update', ... 'BackgroundColor',Theme.color04, ... 'Position',[0.27 0.041 0.187 0.056], ... 'String',{'Voltage Magnitudes','Voltage Angles', ... 'Line Flows','Gen. Rotor Angles', ... 'Gen. Rotor Speeds','LMPs','NCPs'}, ... 'Style','popupmenu', ... 'Tag','PopupMenu2', ... 'Value',1); x = 0.02; y = 0.05; % Frame and push buttons for axis manipulation h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.0726-x 0.0638-y 0.2000 0.0893], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('mat_rotate'), ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','rotate3d(gcf), , if(get(gcbo,''Value'')), set(findobj(gcf,''Tag'',''toggle7''),''Value'',0), zoom(gcf,''off''), end', ... 'Position',[0.0776-x 0.0685-y 0.0600 0.0800], ... 'TooltipString','Rotate graph', ... 'Style','togglebutton', ... 'Tag','toggle5'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('mat_grid'), ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','grid(get(Fig.threed,''UserData''))', ... 'Position',[0.1426-x 0.0685-y 0.0600 0.0800], ... 'TooltipString','Grid', ... 'Style','togglebutton', ... 'Tag','toggle6'); h1 = uicontrol('Parent',h0, ... 'CData',fm_mat('mat_zoomxy'), ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','zoom, if(get(gcbo,''Value'')), set(findobj(gcf,''Tag'',''toggle5''),''Value'',0), rotate3d(gcf,''off''), end', ... 'Position',[0.2076-x 0.0685-y 0.0600 0.0800], ... 'TooltipString','Zoom', ... 'Style','togglebutton', ... 'Tag','toggle7'); if nargout > 0, fig = h0; end function togglecontrols(fig,flag) hdl(1) = findobj(fig,'Tag','PopupMenu1'); hdl(2) = findobj(fig,'Tag','PopupMenu2'); hdl(3) = findobj(fig,'Tag','Frame2'); hdl(4) = findobj(fig,'Tag','toggle5'); hdl(5) = findobj(fig,'Tag','toggle6'); hdl(6) = findobj(fig,'Tag','toggle7'); hdl(7) = findobj(fig,'Tag','Pushbutton1'); hdl(8) = findobj(fig,'Tag','Pushbutton2'); hdl(9) = findobj(fig,'Tag','Pushbutton3'); set(hdl,'Visible',flag)
github
Sinan81/PSAT-master
fm_dirset.m
.m
PSAT-master/psat-oct/psat/fm_dirset.m
30,919
utf_8
5fd21968fdac71735d7ea592d1e51a8e
function varargout = fm_dirset(type) % FM_DIRSET define settings and actions for the data format % conversion GUI % % FM_DIRSET(TYPE) % TYPE action indentifier % %see also FM_DIR % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 05-Jul-2003 %Update: 31-Jul-2003 %Update: 07-Oct-2003 %Version: 1.1.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Path Fig Settings Theme if ishandle(Fig.dir) hdl = findobj(Fig.dir,'Tag','PopupMenu1'); formato = get(hdl,'Value'); hdl_dir = findobj(Fig.dir,'Tag','EditText1'); folder1 = get(hdl_dir,'String'); if ischar(folder1) && isdir(folder1), cd(folder1), end end % codes: IEEE = 1; PSAT = 2; PSATPERT = 3; PSATMDL = 4; CYME = 5; MATPOWER = 6; PST = 7; EPRI = 8; PSSE = 9; PSAP = 10; EUROSTAG = 11; TH = 12; CESI = 13; VST = 14; SIMPOW = 15; NEPLAN = 16; DIGSILENT = 17; POWERWORLD = 18; PET = 19; FLOWDEMO = 20; GEEPC = 21; CHAPMAN = 22; UCTE = 23; PCFLO = 24; WEBFLOW = 25; IPSS = 26; CEPEL = 27; ODM = 28; REDS = 29; VITRUVIO = 30; % all files switch type case 'formatlist' formati = cell(VITRUVIO,1); formati{IEEE} = 'IEEE CDF (.dat, .txt, .cf)'; formati{CYME} = 'CYME (.nnd, .sf)'; formati{MATPOWER} = 'MatPower (.m)'; formati{PSAT} = 'PSAT data (.m)'; formati{PSATPERT} = 'PSAT pert. (.m)'; formati{PSATMDL} = 'PSAT Simulink (.mdl)'; formati{PST} = 'PST (.m)'; formati{EPRI} = 'EPRI (.wsc, .txt, .dat)'; formati{PSSE} = 'PSS/E (.raw)'; formati{PSAP} = 'PSAP (.dat)'; formati{EUROSTAG} = 'Eurostag (.dat)'; formati{TH} = 'TH (.dat)'; formati{CESI} = 'CESI - INPTC1 (.dat)'; formati{VST} = 'VST (.dat)'; formati{SIMPOW} = 'SIMPOW (.optpow)'; formati{NEPLAN} = 'NEPLAN (.ndt)'; formati{DIGSILENT} = 'DigSilent (.dgs)'; formati{POWERWORLD} = 'PowerWorld (.aux)'; formati{PET} = 'PET (.pet)'; formati{FLOWDEMO} = 'Flowdemo.net (.fdn)'; formati{GEEPC} = 'GE format (.epc)'; formati{CHAPMAN} = 'Chapman format'; formati{UCTE} = 'UCTE format'; formati{PCFLO} = 'PCFLO format'; formati{WEBFLOW} = 'WebFlow format'; formati{IPSS} = 'InterPSS format (.ipss)'; formati{CEPEL} = 'CEPEL format (.txt)'; formati{ODM} = 'ODM format (.odm, .xml)'; formati{REDS} = 'REDS format (.pos)'; formati{VITRUVIO} = 'All Files (*.*)'; varargout(1) = {formati}; %================================================================== case 'changedir' hdl = findobj(Fig.dir,'Tag','Listbox1'); cdir = get(hdl,'String'); ndir = get(hdl,'Value'); namedir = cdir{ndir(1),1}; switch namedir case '..' eval('cd ..'); case '.' if ~isempty(dir(namedir)) cd(namedir); end case '[ * DATA * ]' if isempty(Path.data), return, end cd(Path.data) case '[ * PERT * ]' if isempty(Path.pert), return, end cd(Path.pert) case '[ * LOCAL * ]' if isempty(Path.local), return, end cd(Path.local) case '[ * PSAT * ]' if isempty(Path.psat), return, end cd(Path.psat) otherwise cd(namedir) end a = dir; numdir = find([a.isdir] == 1); cdir = {a(numdir).name}'; cdir(strmatch('.',cdir)) = []; cdir(strmatch('@',cdir)) = []; set(hdl,'ListboxTop',1,'String',[{'.'; '..'};cdir;get(hdl,'UserData')],'Value',1); hdl = findobj(Fig.dir,'Tag','EditText1'); set(hdl,'String',pwd); set(Fig.dir,'UserData',pwd); hdl = findobj(Fig.dir,'Tag','Listbox2'); hdlf = findobj(Fig.dir,'Tag','PopupMenu1'); cfile = uform(get(hdlf,'Value')); if isempty(cfile) cfile = 'empty'; else cfile = sort(cfile); end set(hdl,'ListboxTop',1,'String',cfile,'Value',1); %================================================================== case 'chformat' if ~ishandle(Fig.dir), return; end if ~strcmp(get(Fig.dir, 'Type'), 'figure'), return; end hdlf = findobj(Fig.dir,'Tag','PopupMenu1'); formato = get(hdlf,'Value'); if ~length(formato) formato = 1 end % display(formato) hdl = findobj(Fig.dir,'Tag','Listbox2'); hdla = findobj(Fig.dir,'Tag','Axes1'); hdlc = findobj(Fig.dir,'Tag','Pushbutton1'); hdl1 = findobj(Fig.dir,'Tag','CheckboxSilent'); hdl2 = findobj(Fig.dir,'Tag','Checkbox2'); hdl4 = findobj(Fig.dir,'Tag','StaticText2'); hdlp = findobj(Fig.dir,'Tag','PushbuttonPreview'); cfile = uform(formato); switch int32(formato) case IEEE, file = 'ieee'; case CYME, file = 'cyme'; case MATPOWER, file = 'pserc'; case PSAT, file = 'psatdata'; case PSATPERT, file = 'psatpert'; case PSATMDL, file = 'simulink'; case PST, file = 'cherry'; case EPRI, file = 'epri'; case PSSE, file = 'pti'; case PSAP, file = 'pjm'; case EUROSTAG, file = 'eurostag'; case TH, file = 'th'; case CESI, file = 'cesi'; case VST, file = 'cepe'; case SIMPOW, file = 'simpow'; case NEPLAN, file = 'neplan'; case DIGSILENT, file = 'digsilent'; case POWERWORLD, file = 'powerworld'; case PET, file = 'pet'; case FLOWDEMO, file = 'eeh'; case GEEPC, file = 'ge'; case CHAPMAN, file = 'chapman'; case UCTE, file = 'ucte'; case PCFLO, file = 'pcflo'; case WEBFLOW, file = 'webflow'; case IPSS, file = 'ipss'; case CEPEL, file = 'cepel'; case ODM, file = 'odm'; case REDS, file = 'reds'; case VITRUVIO, file = 'vitruvio'; end switch formato case VITRUVIO, if ~get(hdlf,'UserData'), set(hdlc,'Enable','off'), end set(hdl1,'Enable','off') set(hdl2,'Enable','off') set(hdl4,'Enable','off') case PSAT, set(hdlc,'Enable','on') set(hdl1,'Enable','off') if ~get(hdlf,'UserData'), set(hdl2,'Enable','on'), end if ~get(hdlf,'UserData'), set(hdl4,'Enable','on'), end case PSATPERT, if ~get(hdlf,'UserData'), set(hdlc,'Enable','off'), end set(hdl1,'Enable','off') set(hdl2,'Enable','off') set(hdl4,'Enable','off') case {NEPLAN,CESI} set(hdlc,'Enable','on') set(hdl1,'Enable','on') set(hdl2,'Enable','off') set(hdl4,'Enable','off') otherwise % all other formats set(hdlc,'Enable','on') set(hdl1,'Enable','off') set(hdl2,'Enable','off') set(hdl4,'Enable','off') end if formato == PSATMDL set(hdlp,'Enable','on') set(hdlp,'Visible','on') else set(hdlp,'Enable','off') set(hdlp,'Visible','off') end a = imread([Path.images,'logo_',file,'.jpg'],'jpg'); [yl,xl,zl] = size(a); set(Fig.dir,'Units','pixels') figdim = get(Fig.dir,'Position'); % the following if-block is needed for some issues on Matlab R2008a if figdim(3) < 1 if strcmp(get(0,'Units'),'pixels') ssize = get(0,'ScreenSize'); figdim(3) = ssize(3)*figdim(3); figdim(4) = ssize(4)*figdim(4); else set(0,'Units','pixels') ssize = get(0,'ScreenSize'); figdim(3) = ssize(3)*figdim(3); figdim(4) = ssize(4)*figdim(4); end end set(Fig.dir,'Units','normalized') dimx = figdim(3)*0.2616; dimy = figdim(4)*0.3468; rl = xl/yl; if dimx > xl && dimy > yl xd = xl/figdim(3); yd = yl/figdim(4); set(hdla,'Position',[0.8358-xd/2, 0.5722-yd/2, xd, yd]); elseif xl > yl xd = 0.2616; yd = 0.3468/rl; set(hdla,'Position',[0.7050, 0.5722-0.1734/rl, xd, yd]); else xd = 0.2616*rl; yd = 0.3468; set(hdla,'Position',[0.8358-0.1308*rl, 0.3988, xd, yd]); end xd = round(xd*figdim(3)); yd = round(yd*figdim(4)); %disp([xl yl xd yd]) if xd ~= xl && yd ~= yl try if Settings.hostver >= 7.04 a = imresize(a,[yd xd],'bilinear'); else a = imresize(a,[yd xd],'bilinear',11); end catch % imresize is not available!!! end end set(hdla,'XLim',[0.5 xd+0.5],'YLim',[0.5 yd+0.5]); if Settings.hostver < 8.04 if length(get(hdla,'Children')) > 1 h2 = image( ... 'Parent',hdla, ... 'CData',a, ... 'Erase','none', ... 'Tag','Axes1Image1', ... 'XData',[1 xd], ... 'YData',[1 yd]); else set(get(hdla,'Children'),'CData',a,'XData',[1 xd],'YData',[1 yd]); end else if length(get(hdla,'Children')) > 1 set(hdla, 'XDir', 'reverse'); h2 = image( ... 'Parent',hdla, ... 'CData',flipud(a), ... 'Erase','none', ... 'Tag','Axes1Image1', ... 'XData',[1 xd], ... 'YData',[1 yd]); else set(hdla, 'XDir', 'reverse'); set(get(hdla,'Children'), ... 'CData',flipud(a), ... 'XData',[1 xd], ... 'YData',[1 yd]) end end set(hdla,'XTick',[],'XTickLabel','','XColor',Theme.color01); set(hdla,'YTick',[],'YTickLabel','','YColor',Theme.color01); if ispc, set(hdla,'XColor',[126 157 185]/255,'YColor',[126 157 185]/255), end if isempty(cfile), cfile = 'empty'; else, cfile = sort(cfile); end set(hdl,'ListboxTop',1,'String',cfile,'Value',1); Settings.format = formato; %================================================================== case 'editinit' if ~isempty(Path.temp) try cd(Path.temp); catch % nothing to do end elseif ~isempty(Path.data) try cd(Path.data); catch % nothing to do end end set(gcbo,'String',pwd) set(gcf,'UserData',pwd); %================================================================== case 'dirinit' devices = getdevices; devices{end+1,1} = '[ * DATA * ]'; devices{end+1,1} = '[ * PERT * ]'; devices{end+1,1} = '[ * LOCAL * ]'; devices{end+1,1} = '[ * PSAT * ]'; set(gcbo,'UserData',devices) cd(get(gcf,'UserData')) a = dir; numdir = find([a.isdir] == 1); if isempty(numdir) cdir = {' '}; else cdir = {a(numdir).name}'; cdir(strmatch('.',cdir)) = []; cdir(strmatch('@',cdir)) = []; end set(findobj(Fig.dir,'Tag','Listbox1'),'ListboxTop',1, ... 'String',[{'.';'..'}; cdir; devices],'Value',1); %================================================================== case 'dirsel' %values = get(gcbo,'Value'); %set(gcbo,'Value',values(end)); if strcmp(get(Fig.dir,'SelectionType'),'open') cd(Path.local) fm_dirset('changedir'); end %================================================================== case 'diredit' hdl = findobj(Fig.dir,'Tag','EditText1'); cartella = get(hdl,'String'); try cd(cartella); hdl = findobj(Fig.dir,'Tag','Listbox1'); a = dir; cdir = {'.';'..'}; numdir = find([a.isdir] == 1); j = 2; for i = 1:length(numdir) if ~strcmp(a(numdir(i)).name(1),'.') && isunix j = j + 1; cdir{j,1} = a(numdir(i)).name; end end if isempty(cdir), cdir = ' '; else, cdir = sort(cdir); end set(hdl,'ListboxTop',1,'String',[cdir;get(hdl,'UserData')],'Value',1); hdl = findobj(Fig.dir,'Tag','Listbox2'); cfile = uform(formato); if isempty(cfile), cfile = 'empty'; else, cfile = sort(cfile); end set(hdl,'ListboxTop',1,'String',cfile,'Value',1); set(Fig.dir,'UserData',cartella); catch fm_disp(lasterr,2) set(hdl_dir,'String',get(Fig.dir,'UserData')); end %================================================================== case 'getfolder' pathname = get(Fig.dir,'UserData'); cartella = uigetdir(pathname); if cartella hdl = findobj(Fig.dir,'Tag','EditText1'); set(hdl,'String',cartella); cd(Path.local) fm_dirset('diredit'); end %================================================================== case 'convert' hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); nomefile = get(hdl,'String'); if ~iscell(nomefile), nomefile = cellstr(nomefile); end hdl = findobj(Fig.dir,'Tag','PopupMenu1'); if numfile == 1 && strcmp(nomefile{1},'empty') fm_disp('Current folder does not contain files in the selected format.',2) cd(Path.local) return end % if coverting a PSAT file, get destination format hdlpsat = findobj(Fig.dir,'Tag','Checkbox2'); convpsat = get(hdlpsat,'Value'); for i = 1:length(numfile) lasterr(''); filename = nomefile{numfile(i),1}; check = 0; switch get(hdl,'Value') case IEEE check = fm_perl('IEEE CDF','ieee2psat',filename); case CYME check = fm_perl('CYME','cyme2psat',filename); case MATPOWER check = matpower2psat(filename,pwd); case PSAT switch convpsat case 1, check = psat2ieee(filename,pwd); case 2, check = psat2epri(filename,pwd); case 3, check = psat2odm(filename,pwd); end case PSATMDL first = double(filename(1)); if first <= 57 && first >= 48 copyfile(filename,['d',filename]) filename = ['d',filename]; fm_disp(['Use modified file name <',filename,'>']) end check = sim2psat(filename,pwd); case PSATPERT fm_disp('No filter is associated with pertubation files.') case PST check = pst2psat(filename,pwd); case EPRI check = fm_perl('WSCC','epri2psat',filename); case PSSE check = fm_perl('PSS/E','psse2psat',filename); case PSAP check = fm_perl('PSAP','psap2psat',filename); case EUROSTAG check = fm_perl('EUROSTAG','eurostag2psat',filename); case TH, check = fm_perl('TH','th2psat',filename); case CESI, check = fm_perl('CESI','inptc12psat',filename); case VST check = fm_perl('VST','vst2psat',filename); case SIMPOW check = fm_perl('SIMPOW','simpow2psat',filename); case NEPLAN check = fm_perl('NEPLAN','neplan2psat',filename); case DIGSILENT check = fm_perl('DIGSILENT','digsilent2psat',filename); case POWERWORLD check = fm_perl('PowerWorld','pwrworld2psat',filename); case PET fm_choice('Filter for PET data format has not been implemeted yet',2) break case FLOWDEMO check = fm_perl('FlowDemo.net','flowdemo2psat',filename); case GEEPC check = fm_perl('GE','ge2psat',filename); case CHAPMAN check = fm_perl('Chapman','chapman2psat',filename); case UCTE check = fm_perl('UCTE','ucte2psat',filename); case PCFLO check = fm_perl('PCFLO','pcflo2psat',filename); case WEBFLOW check = fm_perl('WebFlow','webflow2psat',filename); case CEPEL check = fm_perl('CEPEL','cepel2psat',filename); case ODM check = fm_perl('ODM','odm2psat',filename); case REDS check = fm_perl('REDS','reds2psat',filename); case IPSS if ~isempty(strfind(filename,'.ipssdat')) check = fm_perl('InterPSS','ipssdat2psat',filename); else check = fm_perl('InterPSS','ipss2psat',filename); end case VITRUVIO % All files fm_disp('Select a Data Format for running the conversion.') end if ~check && ~isempty(lasterr), fm_disp(lasterr), end end if nargout, varargout{1} = check; end %================================================================== case 'openfile' global File Path.temp = 0; File.temp = ''; hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); nomefile = get(hdl,'String'); if ~iscell(nomefile), nomefile = cellstr(nomefile); end if numfile == 1 && strcmp(nomefile{1},'empty') fm_disp('Current folder does not contain files in the selected data format.',2) cd(Path.local) close(Fig.dir) return end hdl = findobj(Fig.dir,'Tag','PopupMenu1'); type = get(hdl,'Value'); if type == PSAT || type == PSATPERT || type == VITRUVIO check = 1; else cd(Path.local) check = fm_dirset('convert'); end if ~check fm_disp('Data conversion failed.',2) return end % determine file name namefile = nomefile{numfile}; switch type case {PSAT,PSATPERT,PSATMDL,VITRUVIO} % nothing to do! case PCFLO namefile = regexprep([namefile,'.m'],'^bdat\.','','ignorecase'); namefile = regexprep(['d_',namefile],'^d*_*','d_'); namefile = regexprep(namefile,'[^\w\.]','_'); case PST namefile = strrep(namefile,'.m','_pst.m'); if ~strcmp(namefile(1), 'd'); namefile = ['d_',namefile]; end case MATPOWER extension = findstr(namefile,'.'); namefile = ['d_',namefile(1:extension(end)-1),'.m']; otherwise namefile = regexprep(['d_',namefile],'^d*_*','d_'); namefile = regexprep(namefile,'^d_d','d_'); namefile = regexprep(namefile,'^d__','d_'); namefile = regexprep(namefile,'[^\w\.]','_'); namefile = regexprep(namefile,'\..+$','.m'); end Path.temp = get(Fig.dir,'UserData'); if ~strcmp(Path.temp(end),filesep) Path.temp = [Path.temp,filesep]; end File.temp = namefile; close(Fig.dir) %================================================================== case 'cancel' Path.temp = 0; File.temp = ''; close(Fig.dir) %================================================================== case 'preview' global File % check whether the selected file is a Simulink model hdl = findobj(Fig.dir,'Tag','PopupMenu1'); type = get(hdl,'Value'); if type ~= PSATMDL cd(Path.local) return end % get the name of the Simulink model hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); if length(numfile) > 1 numfile = numfile(1); temp = get(hdl,'String'); namefile = temp{numfile}; else files = get(hdl,'String'); if iscell(files) namefile = files{numfile}; else namefile = files; end end % make sure that the file name does not start with a number first = double(namefile(1)); if first <= 57 && first >= 48 copyfile(namefile,['d',namefile]) namefile = ['d',namefile]; end oldpath = Path.data; oldfile = File.data; Path.data = pwd; File.data = [namefile(1:end-4),'(mdl)']; hdla = findobj(Fig.dir,'Tag','Axes1'); lasterr('') try fm_simrep('DrawModel',0,0,0) catch disp(' ') fm_disp('* * * The model likely refers to an old PSAT/Simulink library.') fm_disp(' Load and update the model before trying to preview it.') fm_dirset chformat return end %set(hdla,'XLimMode','auto') %set(hdla,'YLimMode','auto') x_lim = get(hdla,'XLim'); y_lim = get(hdla,'YLim'); xl = x_lim(2)-x_lim(1); yl = y_lim(2)-y_lim(1); set(Fig.dir,'Units','pixels') figdim = get(Fig.dir,'Position'); set(Fig.dir,'Units','normalized') dimx = figdim(3)*0.2616; dimy = figdim(4)*0.3468; rl = xl/yl; if dimx > xl && dimy > yl xd = xl/figdim(3); yd = yl/figdim(4); set(hdla,'Position',[0.8358-xd/2, 0.5722-yd/2, xd, yd]); elseif xl > yl xd = 0.2616; yd = 0.3468/rl; set(hdla,'Position',[0.7050, 0.5722-0.1734/rl, xd, yd]); else xd = 0.2616*rl; yd = 0.3468; set(hdla,'Position',[0.8358-0.1308*rl, 0.3988, xd, yd]); end Path.data = oldpath; File.data = oldfile; %================================================================== case 'view' hdl = findobj(Fig.dir,'Tag','Listbox2'); numfile = get(hdl,'Value'); nomefile = get(hdl,'String'); if ~iscell(nomefile), nomefile = cellstr(nomefile); end if strcmp(nomefile{1},'empty') fm_disp('Folder is empty or does not contain files in the selected data format',2) cd(Path.local) return end for i = 1:length(numfile) ext = lower(nomefile{numfile(i),1}(end-2:end)); idx = findstr(ext,'.'); if ~isempty(idx) ext = ext(idx(end)+1:end); end file = nomefile{numfile(i),1}; try switch ext case 'mdl' open_system(file) case 'pdf', switch computer case 'GLNX86', eval(['! xpdf ',file, ' &']), case 'PCWIN', eval(['! acroread ',file, ' &']) otherwise 'SOL2', eval(['! acroread ',file, ' &']) end case '.ps' switch computer case 'GLNX86', eval(['! gsview ',file, ' &']), case 'PCWIN', eval(['! gsview ',file, ' &']) otherwise, eval(['! ghostview ',file, ' &']) end case 'eps' switch computer case 'GLNX86', eval(['! gsview ',file, ' &']), case 'PCWIN', eval(['! gsview ',file, ' &']) otherwise, eval(['! ghostview ',file, ' &']) end case 'doc' switch computer case 'GLNX86', eval(['! AbiWord ',file, ' &']), case 'PCWIN', eval(['! WINWORD ',file, ' &']) otherwise, fm_disp('Unknown viewer on this platform for file "',file,'"') end case 'ppt' switch computer case 'GLNX86', eval(['! AbiWord ',file, ' &']), case 'PCWIN', eval(['! POWERPNT ',file, ' &']) otherwise, fm_disp('Unknown viewer on this platform for file "',file,'"') end case 'dvi' switch computer case 'GLNX86', eval(['! xdvi ',file, ' &']), case 'PCWIN', fm_disp('Unknown viewer on this platform for file "',file,'"') otherwise, eval(['! xdvi ',file, ' &']) end case 'jpg', fm_iview(file) case 'tif', fm_iview(file) case 'gif', fm_iview(file) case 'bmp', fm_iview(file) case 'png', fm_iview(file) case 'hdf', fm_iview(file) case 'pcx', fm_iview(file) case 'xwd', fm_iview(file) case 'ico', fm_iview(file) case 'cur', fm_iview(file) otherwise, fm_text(13,file) end catch fm_disp(['Error in opeining file "',file,'": ',lasterr]) end end end cd(Path.local) %=================================================================== function cfile = uform(formato) % codes IEEE = 1; PSAT = 2; PSATPERT = 3; PSATMDL = 4; CYME = 5; MATPOWER = 6; PST = 7; EPRI = 8; PSSE = 9; PSAP = 10; EUROSTAG = 11; TH = 12; CESI = 13; VST = 14; SIMPOW = 15; NEPLAN = 16; DIGSILENT = 17; POWERWORLD = 18; PET = 19; FLOWDEMO = 20; GEEPC = 21; CHAPMAN = 22; UCTE = 23; PCFLO = 24; WEBFLOW = 25; IPSS = 26; CEPEL = 27; ODM = 28; REDS = 29; VITRUVIO = 30; % all files a = dir; numfile = find([a.isdir] == 0); jfile = 1; cfile = []; for i = 1:length(numfile) nomefile = a(numfile(i)).name; lfile = length(nomefile); add_file = 0; % display(formato) switch int32(formato) case IEEE extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat') || strcmpi(extent,'txt') || ... strcmpi(extent,'.cf'), if isfile(nomefile,'BUS DATA FOLLOW',20) add_file = 1; end end case CYME extent1 = nomefile(max(1,lfile-3):lfile); extent2 = nomefile(max(1,lfile-2):lfile); if strcmpi(extent1,'.nnd') || strcmpi(extent2,'.sf') add_file = 1; end case MATPOWER extent = nomefile(lfile); if strcmpi(extent,'m') if isfile(nomefile,'baseMVA',5), add_file = 1; end end case PSAT extent = nomefile(lfile); if strcmpi(extent,'m') if strcmp(nomefile(1),'d') add_file = 1; elseif isfile(nomefile,'Bus.con',50) add_file = 1; end end case PSATPERT extent = nomefile(lfile); if strcmpi(extent,'m') if strcmp(nomefile(1),'p') add_file = 1; elseif isfile(nomefile,'(t)',5) add_file = 1; end end case PSATMDL extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'mdl') if strcmpi(nomefile,'fm_lib.mdl') add_file = 0; %elseif strcmp(nomefile(1),'d') % add_file = 1; %elseif isfile(nomefile,'PSATblock',1000) %% THIS IS TOO SLOW!! % add_file = 1; else add_file = 1; end end case PST extent = nomefile(lfile); if strcmpi(extent,'m') && strcmp(nomefile(1),'d') if isfile(nomefile,'bus = [',50), add_file = 1; end if ~add_file if isfile(nomefile,'bus=',50), add_file = 1; end end end case EPRI extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'wsc') || strcmpi(extent,'txt') || ... strcmpi(extent,'dat') if isfile(nomefile,'HDG',15) add_file = 1; elseif isfile(nomefile,'/NETWORK_DATA\',20) add_file = 1; end end case PSSE extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'raw'), fid = fopen(nomefile, 'rt'); sline = fgets(fid); out = 0; if isempty(sline), sline = ' 2'; end if sline == -1; sline = ' 2'; end if length(sline) == 1; sline = [sline,' ']; end if isempty(str2num(sline(1:4))), sline = ' 2'; end if str2num(sline(1:2)) == 0 || str2num(sline(1:2)) == 1 out = 1; end if strcmp(sline(1:3),'001'), out = 0; end count = fclose(fid); if out, add_file = 1; end end case PSAP extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), fid = fopen(nomefile, 'rt'); sline = fgets(fid); count = fclose(fid); if strfind(sline,'1'), add_file = 1; end end case EUROSTAG extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), if isfile(nomefile,'HEADER ',20), add_file = 1; end end case TH extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), if isfile(nomefile,'SYSBASE',50) || ... isfile(nomefile,'THLINE',50) add_file = 1; end end case CESI extent = nomefile(max(1,lfile-2):lfile); if strcmpi(extent,'dat'), if isfile(nomefile,'VNOM',25), add_file = 1; end end case VST extent = nomefile(max(1,lfile-7):lfile); if strcmpi(extent,'_vst.dat'), add_file = 1; end case SIMPOW extent = nomefile(max(1,lfile-6):lfile); %if strcmpi(extent,'.optpow') || strcmpi(extent,'.dynpow') if strcmpi(extent,'.optpow'), add_file = 1; end case IPSS extent1 = nomefile(max(1,lfile-7):lfile); extent2 = nomefile(max(1,lfile-4):lfile); if strcmpi(extent1,'.ipssdat') || strcmpi(extent2,'.ipss') add_file = 1; end case NEPLAN extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.ndt'), add_file = 1; end case ODM extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.odm'), add_file = 1; end if strcmpi(extent,'.xml') if isfile(nomefile,'PSSStudyCase',10), add_file = 1; end end case DIGSILENT extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.dgs'), add_file = 1; end case POWERWORLD extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.aux'), add_file = 1; end case PET extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.pet'), add_file = 1; end case FLOWDEMO extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.fdn'), add_file = 1; end case CHAPMAN if isempty(findstr(nomefile,'.')), if isfile(nomefile,'SYSTEM',10), add_file = 1; end end case UCTE extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.uct'), add_file = 1; end case REDS extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.pos') if isfile(nomefile,'.PU',10), add_file = 1; end end case PCFLO if strmatch('bdat.',lower(nomefile)), add_file = 1; end case WEBFLOW extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.txt') if isfile(nomefile,'BQ',10) add_file = 1; end end case CEPEL extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.txt') if isfile(nomefile,'TITU',5) add_file = 1; end end case GEEPC extent = nomefile(max(1,lfile-3):lfile); if strcmpi(extent,'.epc'), add_file = 1; end otherwise % all files % add only files that do not begin with a dot that are % hidden files on UNIX systems if ~(strcmp(nomefile(1),'.') && isunix) add_file = 1; end end if add_file, cfile{jfile,1} = a(numfile(i)).name; jfile = jfile + 1; end end %============================================================================ function out = isfile(file,stringa,nrow) % checking the first nrow to figure out the data format out = 0; [fid, message] = fopen(file, 'rt'); if ~isempty(message) fm_disp(['While inspecting the current folder, ', ... 'error found in file "',file,'". ',message]) return end n_row = 0; while 1 sline = fgets(fid); n_row = n_row + 1; if ~isempty(sline), if sline == -1, break; end, end vec = strfind(sline,stringa); if ~isempty(vec), out = 1; break, end if n_row == nrow, break, end end count = fclose(fid); %============================================================================ function devices = getdevices if isunix devices = {'/'}; else devices = {'a:\'}; ndev = 1; for i = 99:122 device_name = [char(i),':\']; %if exist(device_name) == 7 if ~isempty(dir(device_name)) ndev = ndev + 1; devices{ndev,1} = device_name; end end end %============================================================================ function check = fm_perl(program_name,filter_name,file_name) global Path Fig cmd = [Path.filters,filter_name]; % last minute option for certain filters hdl = findobj(Fig.dir,'Tag','CheckboxSilent'); if ~get(hdl,'Value') switch program_name case 'CESI' [add_file,add_path] = uigetfile('*.dat','Select COLAS ADD file'); if strcmp(add_path,[pwd,filesep]) file_name = ['-a" "',add_file,'" "',file_name]; elseif add_path == 0 % no COLAS ADD file else % COLAS ADD file is not in the current folder fm_disp(['* * COLAS ADD file must be in the same folder as base ' ... 'data file.']) end case 'NEPLAN' [add_file,add_path] = uigetfile('*.edt','Select EDT file'); if strcmp(add_path,[pwd,filesep]) file_name = ['-a" "',add_file,'" "',file_name]; elseif add_path == 0 % no NEPLAN EDT file else % NEPLAN EDT file is not in the current folder fm_disp(['* * NEPLAN EDT file must be in the same folder as NDT ' ... 'file.']) end case 'SIMPOW' [add_file,add_path] = uigetfile('*.dynpow','Select DYNPOW file'); if strcmp(add_path,[pwd,filesep]) file_name = [file_name,'" "',add_file]; elseif add_path == 0 % no DYNPOW file file_name = ['-n" "',file_name]; else file_name = [file_name,'" "',add_path,filesep,add_file]; end otherwise % nothing to do end end % verbose conversion hdl = findobj(Fig.dir,'Tag','CheckboxVerbose'); if get(hdl,'Value') file_name = ['-v" "',file_name]; end if ispc cmdString = ['"',Path.filters,filter_name,'" "',file_name,'"']; else cmdString = [filter_name,' "',file_name,'"']; end % Execute Perl script errTxtNoPerl = 'Unable to find Perl executable.'; if isempty(cmdString) % nothing to do ... elseif ispc % PC perlCmd = fullfile(matlabroot, 'sys\perl\win32\bin\'); cmdString = ['perl ' cmdString]; perlCmd = ['set PATH=',perlCmd, ';%PATH%&' cmdString]; [status, results] = dos(perlCmd); else % UNIX [status, perlCmd] = unix('which perl'); if (status == 0) [status, results] = unix(cmdString); else error(errTxtNoPerl); end end fm_disp(results) check = ~status;
github
Sinan81/PSAT-master
fm_input.m
.m
PSAT-master/psat-oct/psat/fm_input.m
13,124
utf_8
a4a7b367ecb64f3f86fd6e1ea1f62c27
function Answer = fm_input(Prompt, Title, NumLines, DefAns,Resize) %INPUTDLG Input dialog box. % Answer = INPUTDLG(Prompt) creates a modal dialog box that returns % user input for multiple prompts in the cell array Answer. Prompt % is a cell array containing the Prompt strings. % % INPUTDLG uses WAITFOR to suspend execution until the user responds. % % Answer = INPUTDLG(Prompt,Title) specifies the Title for the dialog. % % Answer = INPUTDLG(Prompt,Title,LineNo) specifies the number of lines % for each answer in LineNo. LineNo may be a constant value or a % column vector having one element per Prompt that specifies how many % lines per input. LineNo may also be a matrix where the first % column specifies how many rows for the input field and the second % column specifies how many columns wide the input field should be. % % Answer = INPUTDLG(Prompt,Title,LineNo,DefAns) specifies the default % answer to display for each Prompt. DefAns must contain the same % number of elements as Prompt and must be a cell array. % % Answer = INPUTDLG(Prompt,Title,LineNo,DefAns,AddOpts) specifies whether % the dialog may be resized or not. Acceptable values for AddOpts are % 'on' or 'off'. If the dialog can be resized, then the dialog is % not modal. % % AddOpts may also be a data structure with fields Resize, % WindowStyle and Interpreter. Resize may be 'on' or 'off'. % WindowStyle may be 'modal' or 'normal' and Interpreter may be % 'tex' or 'none'. The interpreter applies to the prompt strings. % % Examples: % % prompt={'Enter the matrix size for x^2:','Enter the colormap name:'}; % def={'20','hsv'}; % dlgTitle='Input for Peaks function'; % lineNo=1; % answer=fm_input(prompt,dlgTitle,lineNo,def); % % AddOpts.Resize='on'; % AddOpts.WindowStyle='normal'; % AddOpts.Interpreter='tex'; % answer=fm_input(prompt,dlgTitle,lineNo,def,AddOpts); % % See also TEXTWRAP, QUESTDLG, WAITFOR. % Loren Dean May 24, 1995. % Copyright 1998-2001 The MathWorks, Inc. % $Revision: 1.57 $ % %Modified by: Federico Milano %Date: 11-Nov-2002 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html global Settings Black =[0 0 0 ]/255; LightGray =[192 192 192 ]/255; LightGray2 =[160 160 164 ]/255; MediumGray =[128 128 128 ]/255; White =[255 255 255 ]/255; %%%%%%%%%%%%%%%%%%%% %%% Nargin Check %%% %%%%%%%%%%%%%%%%%%%% if nargin == 1 && nargout == 0, if strcmp(Prompt,'InputDlgResizeCB'), LocalResizeFcn(gcbf) return end end error(nargchk(1,5,nargin)); if Settings.hostver > 6, error(nargoutchk(1,1,nargout)); end if nargin==1, Title=' '; end if nargin<=2, NumLines=1;end if ~iscell(Prompt), Prompt={Prompt}; end NumQuest=prod(size(Prompt)); if nargin<=3, DefAns=cell(NumQuest,1); for lp=1:NumQuest, DefAns{lp}=''; end end WindowStyle='modal'; Interpreter='none'; if nargin<=4, Resize = 'off'; end if nargin==5 && isstruct(Resize), Interpreter=Resize.Interpreter; WindowStyle=Resize.WindowStyle; Resize=Resize.Resize; end if strcmp(Resize,'on'), WindowStyle='normal'; end % Backwards Compatibility if ischar(NumLines), warning(['Please see the INPUTDLG help for correct input syntax.' 10 ... ' OKCallback no longer supported.' ]); NumLines=1; end [rw,cl]=size(NumLines); OneVect = ones(NumQuest,1); if (rw == 1 && cl == 2) NumLines=NumLines(OneVect,:); elseif (rw == 1 && cl == 1) NumLines=NumLines(OneVect); elseif (rw == 1 && cl == NumQuest) NumLines = NumLines'; elseif rw ~= NumQuest || cl > 2, error('NumLines size is incorrect.') end if ~iscell(DefAns), error('Default Answer must be a cell array in INPUTDLG.'); end %%%%%%%%%%%%%%%%%%%%%%% %%% Create InputFig %%% %%%%%%%%%%%%%%%%%%%%%%% FigWidth=300;FigHeight=100; FigPos(3:4)=[FigWidth FigHeight]; FigColor=get(0,'Defaultuicontrolbackgroundcolor'); TextForeground = Black; if sum(abs(TextForeground - FigColor)) < 1 TextForeground = White; end InputFig=dialog( ... 'Visible' ,'off' , ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'points' , ... 'UserData' ,'' , ... 'Tag' ,Title , ... 'HandleVisibility','on' , ... 'Color' ,FigColor , ... 'NextPlot' ,'add' , ... 'WindowStyle' ,WindowStyle, ... 'Resize' ,Resize ... ); %%%%%%%%%%%%%%%%%%%%% %%% Set Positions %%% %%%%%%%%%%%%%%%%%%%%% DefOffset=5; SmallOffset=2; DefBtnWidth=50; BtnHeight=20; BtnYOffset=DefOffset; BtnFontSize=get(0,'FactoryUIControlFontSize'); BtnWidth=DefBtnWidth; TextInfo.Units ='points' ; TextInfo.FontSize =BtnFontSize; TextInfo.HorizontalAlignment='left' ; TextInfo.HandleVisibility ='callback' ; StInfo=TextInfo; StInfo.Style ='text' ; StInfo.BackgroundColor =FigColor; StInfo.ForegroundColor =TextForeground ; TextInfo.VerticalAlignment='bottom'; EdInfo=StInfo; EdInfo.Style='edit'; EdInfo.BackgroundColor=White; BtnInfo=StInfo; BtnInfo.Style='pushbutton'; BtnInfo.HorizontalAlignment='center'; % Determine # of lines for all Prompts ExtControl=uicontrol(StInfo, ... 'String' ,'' , ... 'Position' ,[DefOffset DefOffset ... 0.96*(FigWidth-2*DefOffset) BtnHeight ... ] , ... 'Visible' ,'off' ... ); WrapQuest=cell(NumQuest,1); QuestPos=zeros(NumQuest,4); for ExtLp=1:NumQuest, if size(NumLines,2)==2 [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),NumLines(ExtLp,2)); else, [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),80); end end % for ExtLp delete(ExtControl); QuestHeight=QuestPos(:,4); TxtHeight=QuestHeight(1)/size(WrapQuest{1,1},1); EditHeight=TxtHeight*NumLines(:,1); EditHeight(NumLines(:,1)==1)=EditHeight(NumLines(:,1)==1)+4; FigHeight=(NumQuest+2)*DefOffset + ... BtnHeight+sum(EditHeight) + ... sum(QuestHeight); TxtXOffset=DefOffset; TxtWidth=FigWidth-2*DefOffset; QuestYOffset=zeros(NumQuest,1); EditYOffset=zeros(NumQuest,1); QuestYOffset(1)=FigHeight-DefOffset-QuestHeight(1); EditYOffset(1)=QuestYOffset(1)-EditHeight(1);% -SmallOffset; for YOffLp=2:NumQuest, QuestYOffset(YOffLp)=EditYOffset(YOffLp-1)-QuestHeight(YOffLp)-DefOffset; EditYOffset(YOffLp)=QuestYOffset(YOffLp)-EditHeight(YOffLp); %-SmallOffset; end % for YOffLp QuestHandle=[]; EditHandle=[]; FigWidth =1; AxesHandle=axes('Parent',InputFig,'Position',[0 0 1 1],'Visible','off'); for lp=1:NumQuest, QuestTag=['Prompt' num2str(lp)]; EditTag=['Edit' num2str(lp)]; if ~ischar(DefAns{lp}), delete(InputFig); error('Default answers must be strings in INPUTDLG.'); end QuestHandle(lp)=text('Parent',AxesHandle, ... TextInfo , ... 'Position' ,[ TxtXOffset QuestYOffset(lp)], ... 'String' ,WrapQuest{lp} , ... 'Color' ,TextForeground , ... 'Interpreter',Interpreter , ... 'Tag' ,QuestTag ... ); EditHandle(lp)=uicontrol(InputFig ,EdInfo , ... 'Max' ,NumLines(lp,1) , ... 'Position' ,[ TxtXOffset EditYOffset(lp) ... TxtWidth EditHeight(lp) ... ] , ... 'String' ,DefAns{lp} , ... 'Tag' ,QuestTag ... ); if size(NumLines,2) == 2, set(EditHandle(lp),'String',char(ones(1,NumLines(lp,2))*'x')); Extent = get(EditHandle(lp),'Extent'); NewPos = [TxtXOffset EditYOffset(lp) Extent(3) EditHeight(lp) ]; NewPos1= [TxtXOffset QuestYOffset(lp)]; set(EditHandle(lp),'Position',NewPos,'String',DefAns{lp}) set(QuestHandle(lp),'Position',NewPos1) FigWidth=max(FigWidth,Extent(3)+2*DefOffset); else FigWidth=max(175,TxtWidth+2*DefOffset); end end % for lp FigPos=get(InputFig,'Position'); Temp=get(0,'Units'); set(0,'Units','points'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',Temp); FigWidth=max(FigWidth,2*(BtnWidth+DefOffset)+DefOffset); FigPos(1)=(ScreenSize(3)-FigWidth)/2; FigPos(2)=(ScreenSize(4)-FigHeight)/2; FigPos(3)=FigWidth; FigPos(4)=FigHeight; set(InputFig,'Position',FigPos); CBString='set(gcbf,''UserData'',''Cancel'');uiresume'; CancelHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[FigWidth-BtnWidth-DefOffset DefOffset ... BtnWidth BtnHeight ... ] , ... 'String' ,'Cancel' , ... 'Callback' ,CBString , ... 'Tag' ,'Cancel' ... ); CBString='set(gcbf,''UserData'',''OK'');uiresume'; OKHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[ FigWidth-2*BtnWidth-2*DefOffset DefOffset ... BtnWidth BtnHeight ... ] , ... 'String' ,'OK' , ... 'Callback' ,CBString , ... 'Tag' ,'OK' ... ); Data.OKHandle = OKHandle; Data.CancelHandle = CancelHandle; Data.EditHandles = EditHandle; Data.QuestHandles = QuestHandle; Data.LineInfo = NumLines; Data.ButtonWidth = BtnWidth; Data.ButtonHeight = BtnHeight; Data.EditHeight = TxtHeight+4; Data.Offset = DefOffset; set(InputFig ,'Visible','on','UserData',Data); % This drawnow is a hack to work around a bug drawnow set(findall(InputFig),'Units','normalized','HandleVisibility','callback'); set(InputFig,'Units','points') try uiwait(InputFig); catch delete(InputFig); end TempHide=get(0,'ShowHiddenHandles'); set(0,'ShowHiddenHandles','on'); if any(get(0,'Children')==InputFig), Answer={}; if strcmp(get(InputFig,'UserData'),'OK'), Answer=cell(NumQuest,1); for lp=1:NumQuest, Answer(lp)=get(EditHandle(lp),{'String'}); end % for end % if strcmp delete(InputFig); else, Answer={}; end % if any set(0,'ShowHiddenHandles',TempHide); function LocalResizeFcn(FigHandle) Data=get(FigHandle,'UserData'); %Data.ButtonHandles = [ OKHandles CancelHandle]; %Data.EditHandles = EditHandle; %Data.QuestHandles = QuestHandle; %Data.LineInfo = NumLines; %Data.ButtonWidth = BtnWidth; %Data.ButtonHeight = BtnHeight; %Data.EditHeight = TxtHeight; set(findall(FigHandle),'Units','points'); FigPos = get(FigHandle,'Position'); FigWidth = FigPos(3); FigHeight = FigPos(4); OKPos = [ FigWidth-Data.ButtonWidth-Data.Offset Data.Offset ... Data.ButtonWidth Data.ButtonHeight ]; CancelPos =[Data.Offset Data.Offset Data.ButtonWidth Data.ButtonHeight]; set(Data.OKHandle,'Position',OKPos); set(Data.CancelHandle,'Position',CancelPos); % Determine the height of all question fields YPos = sum(OKPos(1,[2 4]))+Data.Offset; QuestPos = get(Data.QuestHandles,{'Extent'}); QuestPos = cat(1,QuestPos{:}); QuestPos(:,1) = Data.Offset; RemainingFigHeight = FigHeight - YPos - sum(QuestPos(:,4)) - ... Data.Offset - size(Data.LineInfo,1)*Data.Offset; Num1Liners = length(find(Data.LineInfo(:,1)==1)); RemainingFigHeight = RemainingFigHeight - ... Num1Liners*Data.EditHeight; Not1Liners = find(Data.LineInfo(:,1)~=1); %Scale the 1 liner heights appropriately with remaining fig height TotalLines = sum(Data.LineInfo(Not1Liners,1)); % Loop over each quest/text pair for lp = 1:length(Data.QuestHandles), CurPos = get(Data.EditHandles(lp),'Position'); NewPos = [Data.Offset YPos CurPos(3) Data.EditHeight ]; if Data.LineInfo(lp,1) ~= 1, NewPos(4) = RemainingFigHeight*Data.NumLines(lp,1)/TotalLines; end set(Data.EditHandles(lp),'Position',NewPos) YPos = sum(NewPos(1,[2 4])); QuestPos(lp,2) = YPos;QuestPos(lp,3) = NewPos(3); set(Data.QuestHandles(lp),'Position',QuestPos(lp,:)); YPos = sum(QuestPos(lp,[2 4]))+Data.Offset; end if YPos>FigHeight - Data.Offset, FigHeight = YPos+Data.Offset; FigPos(4)=FigHeight; set(FigHandle,'Position',FigPos); drawnow end set(FigHandle,'ResizeFcn','fm_input InputDlgResizeCB'); set(findall(FigHandle),'Units','normalized')
github
Sinan81/PSAT-master
zbuildpi.m
.m
PSAT-master/psat-oct/psat/zbuildpi.m
3,207
utf_8
77e32ffc8651729d7ba2a3fb4c88cb6c
% This program forms the complex bus impedance matrix by the method % of building algorithm. Bus zero is taken as reference. % This program is compatible with power flow data. % Copyright (C) 1998 by H. Saadat. function [Zbus, linedata] = zbuildpi(linedata, gendata, yload) % gendata generator data syn.con ng = length(gendata(:,1)); nlg = gendata(:,1); nrg = zeros(size(gendata(:,1))); zg = gendata(:,7) + j*gendata(:,6); nl = linedata(:,1); nr = linedata(:,2); R = linedata(:,8); X = linedata(:,9); ZB = R + j*X; nbr = length(linedata(:,1)); nbus = max(max(nl), max(nr)); nc = length(linedata(1,:)); BC = 0.5*linedata(:,10); yc = zeros(nbus,1); nlc = zeros(nbus,1); nrc = zeros(nbus,1); for n = 1:nbus yc(n) = 0; nlc(n) = 0; nrc(n) = n; for k = 1:nbr if nl(k) == n || nr(k) == n yc(n) = yc(n) + j*BC(k); end end end if exist('yload') == 1 yload = yload.'; yc = yc + yload; end m = 0; havecc = 0; % have cc ? for n = 1:nbus if abs(yc(n)) ~=0 m = m + 1; nlcc(m) = nlc(n); nrcc(m) = nrc(n); zc(m) = 1/yc(n); havecc = 1; end end if havecc == 1 nlcc = nlcc'; nrcc = nrcc'; zc = zc.'; nl = [nlg; nlcc; nl]; nr = [nrg; nrcc; nr]; ZB = [zg; zc; ZB]; else nl = [nlg; nl]; nr = [nrg; nr]; ZB = [zg; ZB]; end % standard line data consist of line generator capacitor of line model and load linedata = [nl nr real(ZB) imag(ZB)]; nbr = length(nl); Zbus = zeros(nbus, nbus); tree = 0; %%%%new % Adding a branch from a new bus to reference bus 0 for I = 1:nbr ntree(I) = 1; if nl(I) == 0 || nr(I) == 0 if nl(I) == 0 n = nr(I); elseif nr(I) == 0 n = nl(I); end if abs(Zbus(n, n)) == 0 Zbus(n,n) = ZB(I); tree = tree+1; %%new else Zbus(n,n) = Zbus(n,n)*ZB(I)/(Zbus(n,n) + ZB(I)); end ntree(I) = 2; end end % Adding a branch from new bus to an existing bus while tree < nbus %%% new for n = 1:nbus nadd = 1; if abs(Zbus(n,n)) == 0 for I = 1:nbr if nadd == 1 if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end if abs(Zbus(k,k)) ~= 0 for m = 1:nbus if m ~= n Zbus(m,n) = Zbus(m,k); Zbus(n,m) = Zbus(m,k); end end Zbus(n,n) = Zbus(k,k) + ZB(I); tree=tree+1; %%new nadd = 2; ntree(I) = 2; end end end end end end end %%%%%%new % Adding a link between two old buses for n = 1:nbus for I = 1:nbr if ntree(I) == 1 if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end DM = Zbus(n,n) + Zbus(k,k) + ZB(I) - 2*Zbus(n,k); for jj = 1:nbus AP = Zbus(jj,n) - Zbus(jj,k); for kk = 1:nbus AT = Zbus(n,kk) - Zbus(k, kk); DELZ(jj,kk) = AP*AT/DM; end end Zbus = Zbus - DELZ; ntree(I) = 2; end end end end disp('end of zbus build')
github
Sinan81/PSAT-master
fm_gams.m
.m
PSAT-master/psat-oct/psat/fm_gams.m
45,016
utf_8
37a2129685b6794bad0fe98843d008ce
function fm_gams % FM_GAMS initialize and call GAMS to solve % several kind of Market Clearing Mechanisms % % FM_GAMS % %GAMS settings are stored in the structure GAMS, with %the following fields: % % METHOD 1 -> simple auction % 2 -> linear OPF (DC power flow) % 3 -> nonlinear OPF (AC power flow) % 4 -> nonlinear VSC-OPF % 5 -> maximum loading condition % 6 -> continuation OPF % % TYPE 1 -> single period auction % 2 -> multi period auction % 3 -> VSC single period auction % 4 -> VSC multi period auction % %see also FM_GAMS.GMS, FM_GAMSFIG and %structures CPF and OPF for futher settings % %Author: Federico Milano %Date: 29-Jan-2003 %Update: 01-Feb-2003 %Update: 06-Feb-2003 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE OPF CPF GAMS Bus File clpsat global Path Settings Snapshot Varname global PV PQ SW Line Shunt jay Varout global Supply Demand Rmpl Rmpg Ypdp [u,w] = system('gams'); if u fm_disp('GAMS is not properly installed on your system.',2) return end if ~autorun('PSAT-GAMS Interface',0) return end if DAE.n fm_disp(['Dynamic data are not supported within the PSAT-GAMS interface.'],2) return end if ~Supply.n, fm_disp(['Supply data have to be specified before in order to ', ... 'run PSAT-GAMS interface'],2) return end if ~Demand.n, if GAMS.basepg && ~clpsat.init Settings.ok = 0; uiwait(fm_choice(['Exclude (recommended) base generator powers?'])) GAMS.basepg = ~Settings.ok; end noDem = 1; Demand = add_demand(Demand,'dummy'); else noDem = 0; end length(Snapshot.y); if ~GAMS.basepl buspl = Snapshot(1).Pl; busql = Snapshot(1).Ql; Bus.Pl(:) = 0; Bus.Ql(:) = 0; PQ = pqzero_pq(PQ,'all'); end if ~GAMS.basepg ploss = Snapshot(1).Ploss; Snapshot(1).Ploss = 0; buspg = Snapshot(1).Pg; busqg = Snapshot(1).Qg; Bus.Pg(:) = 0; Bus.Qg(:) = 0; SW = swzero_sw(SW,'all'); PV = pvzero_pv(PV,'all'); end fm_disp fm_disp('---------------------------------------------------------') fm_disp(' PSAT-GAMS Interface') fm_disp('---------------------------------------------------------') fm_disp tic method = GAMS.method; modelstat = 0; solvestat = 0; type = GAMS.type; omega = GAMS.omega; if GAMS.method == 6 && GAMS.type ~= 1 fm_disp(['WARNING: Continuation OPF can be run only with Single' ... ' Period Auctions.']) fm_disp('Voltage Stability Constrained OPF will be solved.') method = 4; end if GAMS.method == 6 && GAMS.flow ~= 1 fm_disp(['WARNING: Continuation OPF can be run only with Current ' ... 'Limits.']) fm_disp('Current limits in transmission lines will be used.') GAMS.flow = 1; end if GAMS.type == 3 && GAMS.method ~= 4 fm_disp(['WARNING: Pareto Set Single Period Auction can be run ' ... 'only for VSC-OPF.']) fm_disp( ' Single Period Auction will be solved.') fm_disp type = 1; end if GAMS.type == 3 && length(GAMS.omega) == 1 fm_disp(['WARNING: Weighting factor is scalar. ', ... 'Single Period Auction will be solved.']) fm_disp type = 1; end if GAMS.type == 1 && length(GAMS.omega) > 1 fm_disp(['WARNING: Weighting factor is a vector. ', ... 'First omega entry will be used.']) fm_disp omega = omega(1); end if ~rem(GAMS.type,2) && ~Rmpg.n type = 1; fm_disp(['WARNING: No Ramping data were found. ', ... 'Single Period Auction will be solved.']) fm_disp end if GAMS.type == 2 && Rmpg.n && ~Ypdp.n type = 4; fm_disp(['WARNING: No Power Demand Profile was found. Single ' ... 'Period Auction with Unit Commitment will be solved.']) fm_disp end % resetting time vector in case of previous time simulations if type == 3, Varout.t = []; end switch method case 1, fm_disp(' Simple Auction') case 2, fm_disp(' Market Clearing Mechanism') case 3, fm_disp(' Standard OPF') case 4, fm_disp(' Voltage Stability Constrained OPF') case 5, fm_disp(' Maximum Loading Condition') case 6, fm_disp(' Continuation OPF') case 7, fm_disp(' Congestion Management') end switch type case 1, fm_disp(' Single-Period Auction') case 2, fm_disp(' Multi-Period Auction') case 3, fm_disp(' Pareto Set Single-Period Auction') case 4, fm_disp(' Single-Period Auction with Unit Commitment') end if (GAMS.flatstart || isempty(Snapshot)) && GAMS.method > 2 DAE.y(Bus.a) = getzeros_bus(Bus); DAE.y(Bus.v) = getones_bus(Bus); else DAE.y = Snapshot(1).y; end % ------------------------------------------------------------ % Parameter definition % ------------------------------------------------------------ % dimensions nBus = int2str(Bus.n); nQg = int2str(PV.n+SW.n); nBusref = int2str(SW.refbus); [nSW,SW_idx,ksw] = gams_sw(SW); [nPV,PV_idx,kpv] = gams_pv(PV); [nLine,L,Li,Lj,Gh,Bh,Ghc,Bhc] = gams_line(Line,method); [Gh,Bh,Ghc,Bhc] = gams_shunt(Shunt,method,Gh,Bh,Ghc,Bhc); [nPd,Pd_idx,D] = gams_demand(Demand); [nPs,Ps_idx,S] = gams_supply(Supply,type); [nH,Ch] = gams_ypdp(Ypdp,type); % indexes iBPs = Supply.bus; iBPd = Demand.bus; iBQg = [SW.bus; PV.bus]; % Fixed powers Pg0 = Bus.Pg; Pl0 = Bus.Pl; Ql0 = Bus.Ql; % Generator reactive powers and associated limits Qg0 = getzeros_bus(Bus); Qg0(iBQg) = Bus.Qg(iBQg); [Qgmax,Qgmin] = fm_qlim('all'); % Voltage limits V0 = DAE.y(Bus.v); t0 = DAE.y(Bus.a); [Vmax,Vmin] = fm_vlim(1.5,0.2); % ------------------------------------------------------------ % Data structures % ------------------------------------------------------------ X.val = [V0,t0,Pg0,Qg0,Pl0,Ql0,Qgmax,Qgmin,Vmax,Vmin,ksw,kpv]; lambda.val = [GAMS.lmin(1),GAMS.lmax(1),GAMS.omega(1),GAMS.line]; X.labels = {cellstr(num2str(Bus.a)), ... {'V0','t0','Pg0','Qg0','Pl0','Ql0', ... 'Qgmax','Qgmin','Vmax','Vmin','ksw','kpv'}}; lambda.labels = {'lmin','lmax','omega','line'}; X.name = 'X'; lambda.name = 'lambda'; % ------------------------------------------------------------ % Launch GAMS solver % ------------------------------------------------------------ control = int2str(method); flow = int2str(GAMS.flow); currentpath = pwd; file = 'fm_gams'; if ~rem(type,2) file = [file,'2']; end if GAMS.libinclude file = [file,' ',GAMS.ldir]; end if clpsat.init || ispc, cd(Path.psat), end switch control % ------------------------------------------------------------------ case '1' % S I M P L E A U C T I O N % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV, ... nBusref,control,flow,S,D,X); [Pij,Pji,Qg] = updatePF(Pd,Ps,iBQg); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV, ... nBusref,nH,control,flow,S,D,X,Ch); numh = size(MCP,1); a = zeros(numh,Bus.n); V = zeros(numh,Bus.n); Qg = zeros(numh,Bus.n); Pij = zeros(numh,Line.n); Qij = zeros(numh,Line.n); for i = 1:numh [Piji,Pjii,Qgi] = updatePF(Pd(i,:)',Ps(i,:)',iBQg); a(i,:) = [DAE.y(Bus.a)]'; V(i,:) = [DAE.y(Bus.v)]'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; Qg(i,iBQg) = Qgi'; end ro = MCP*ones(1,Bus.n); end % ------------------------------------------------------------------ case '2' % M A R K E T C L E A R I N G M E C H A N I S M % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus, ... nLine,nPs,nPd,nSW,nPV,nBusref,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx, ... S,D,X,L); [Pij,Pji,Qg] = updatePF(Pd,Ps,iBQg); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,MCP,modelstat,solvestat] = psatgams(file,nBus, ... nLine,nPs,nPd,nSW,nPV,nBusref,nH,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx, ... S,D,X,L,Ch); numh = size(MCP,1); a = zeros(numh,Bus.n); V = zeros(numh,Bus.n); Qg = zeros(numh,Bus.n); Pij = zeros(numh,Line.n); Qij = zeros(numh,Line.n); for i = 1:numh [Piji,Pjii,Qgi] = updatePF(Pd(i,:)',Ps(i,:)',iBQg); a(i,:) = [DAE.y(Bus.a)]'; V(i,:) = [DAE.y(Bus.v)]'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; Qg(i,iBQg) = Qgi'; end ro = MCP; end % ------------------------------------------------------------------ case '3' % S T A N D A R D O P T I M A L P O W E R F L O W % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,S,D,X,L); NCP = compNCP(V,a,mV,mFij,mFji); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref,nH,control, ... flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,S,D,X,L,Ch); NCP = zeros(length(Ps(:,1)),Bus.n); for i = 1:length(Ps(:,1)) NCPi = compNCP(V(i,:)',a(i,:)',mV(i,:)',mFij(i,:)',mFji(i,:)'); NCP(i,:) = NCPi'; end end % ------------------------------------------------------------------ case '7' % C O N G E S T I O N M A N A G E M E N T % ------------------------------------------------------------------ %lambda_values = [0.0:0.01:0.61]; %n_lambda = length(lambda_values); %GAMS.dpgup = zeros(Supply.n,n_lambda); %GAMS.dpgdw = zeros(Supply.n,n_lambda); %GAMS.dpdup = zeros(Demand.n,n_lambda); %GAMS.dpddw = zeros(Demand.n,n_lambda); %for i = 1:length(lambda_values) %lambda.val(1) = lambda_values(i); iteration = 0; idx_gen = zeros(Supply.n,1); Psc_idx = Ps_idx; Psm_idx = zeros(Bus.n,Supply.n); while 1 [Ps,Pd,dPSup,dPSdw,dPDup,dPDdw,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji, ... lambdac,kg,Vc,ac,Qgc,Pijc,Pjic,Pceq,lambdam,modelstat,solvestat] = ... psatgams('fm_cong',nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Psc_idx,Psm_idx,Pd_idx, ... SW_idx,PV_idx,S,D,X,L,lambda); iteration = iteration + 1; if iteration > 10 fm_disp('* * * Maximum number of iteration with no convergence!') break end idx = psupper_supply(Supply,(1+lambdac+kg)*Ps); if sum(idx_gen(idx)) == length(idx) fm_disp(['* * * iter = ',num2str(iteration), ... ', #viol., ',num2str(length(find(idx_gen))), ... ' lambda = ', num2str(lambdac), ... ' kg = ', num2str(kg)]) break else % loop until there are no violations of power supply limits idx_gen(idx) = 1; fm_disp(['* * * iter = ',num2str(iteration),', #viol. = ', ... num2str(length(idx)),', lambda = ', ... num2str(lambdac),' kg = ', num2str(kg)]) drawnow; Psc_idx = psidx_supply(Supply,~idx_gen); Psm_idx = psidx_supply(Supply,idx_gen); end end %GAMS.dpgup(:,i) = dPSup; %GAMS.dpgdw(:,i) = dPSdw; %GAMS.dpdup(:,i) = dPDup; %GAMS.dpddw(:,i) = dPDdw; %if ~rem(i,10), disp(['Current lambda = ',num2str(lambda_values(i))]),end %end %GAMS.lvals = lambda_values; NCP = compNCP(V,a,mV,mFij,mFji); % ------------------------------------------------------------------ case '4' % V O L T A G E S T A B I L I T Y C O N S T R A I N E D % O P T I M A L P O W E R F L O W % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji, ... lambdac,kg,Vc,ac,Qgc,Pijc,Pjic,Pceq,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx,S,D,X,L,lambda); NCP = compNCP(V,a,mV,mFij,mFji); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,V,a,Qg,ro,Pij,Pji,mV,mFij,mFji, ... lambdac,kg,Vc,ac,Qgc,Pijc,Pjic,Pceq,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nH,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,S,D,X,L,lambda,Ch); NCP = zeros(length(lambdac),Bus.n); for i = 1:length(lambdac) NCPi = compNCP(V(i,:)',a(i,:)',mV(i,:)',mFij(i,:)',mFji(i,:)'); NCP(i,:) = NCPi'; end elseif type == 3 % Pareto Set Single Period Auction fm_disp for i = 1:length(omega) fm_disp(sprintf(' VSC-OPF #%d, %3.1f%% - omega: %5.4f', ... i,100*i/length(omega),omega(i))) lambda.val = [GAMS.lmin(1),GAMS.lmax(1),omega(i),GAMS.line]; [Psi,Pdi,Vi,ai,Qgi,roi,Piji,Pjii,mV,mFij,mFji, ... lambdaci,kgi,Vci,aci,Qgci,Pijci,Pjici,Pceq,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx, ... S,D,X,L,lambda); gams_mstat(modelstat) gams_sstat(solvestat) Ps(i,:) = Psi'; Pd(i,:) = Pdi'; V(i,:) = Vi'; a(i,:) = ai'; Qg(i,:) = Qgi'; ro(i,:) = roi'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; lambdac(i,:) = lambdaci'; kg(i,:) = kgi'; Vc(i,:) = Vci'; ac(i,:) = aci'; Qgc(i,:) = Qgci'; Pijc(i,:) = Pijci'; Pjic(i,:) = Pjici'; NCPi = compNCP(Vi,ai,mV,mFij,mFji); NCP(i,:) = NCPi'; end fm_disp end % ------------------------------------------------------------------ case '5' % M A X I M U M L O A D I N G C O N D I T I O N % ------------------------------------------------------------------ if type == 1 % Single Period Auction [Ps,Pd,V,a,Qg,ro,Pij,Pji,lambdac,kg,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref, ... control,flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx, ... SW_idx,PV_idx,S,D,X,L); elseif ~rem(type,2) % Single/Multi Period Auction with UC [Ps,Pd,V,a,Qg,ro,Pij,Pji,lambdac,kg,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nSW,nPV,nBusref,nH, ... control,flow,Gh,Bh,Li,Lj,Ps_idx,Pd_idx,SW_idx, ... PV_idx,S,D,X,L,Ch); end % ------------------------------------------------------------------ case '6' % C O N T I N U A T I O N % O P T I M A L P O W E R F L O W % ------------------------------------------------------------------ initial_time = clock; if type == 1 % single period OPF, no discrete variables % number of steps i = 0; last_point = 0; % initial lambda = 0. Base case has to be feasible lmin = 0; lmax = 0; Lambda = lmin; % save actual CPF settings CPF_old = CPF; %CPF.nump = 50; CPF.show = 0; CPF.type = 3; CPF.sbus = 0; CPF.vlim = 1; CPF.ilim = 1; CPF.qlim = 1; CPF.init = 0; CPF.step = 0.25; control = '6'; % save actual power flow data % ------------------------------------------------------ snappg = Snapshot(1).Pg; %Snapshot(1).Pg = []; Bus_old = Bus; % defining voltage limits [Vmax,Vmin] = fm_vlim(1.2,0.8); fm_disp stop_opf = 0; while 1 % OPF step % ------------------------------------------------------ i = i + 1; fm_disp(sprintf('Continuation OPF #%d, lambda_c = %5.4f', ... i,lmin)) lambda.val = [lmin,lmax,0,GAMS.line]; % call GAMS [Psi,Pdi,Vi,ai,Qgi,roi,Piji,Pjii,mV,mFij,mFji, ... lambdaci,kgi,Vci,aci,Qgci,Pijci,Pjici,mPceq,ml,modelstat,solvestat] = ... psatgams(file,nBus,nLine,nPs,nPd,nBusref,nSW,nPV,control,flow, ... Gh,Bh,Ghc,Bhc,Li,Lj,Ps_idx,Pd_idx,SW_idx,PV_idx,S,D,X,L,lambda); gams_mstat(modelstat) gams_sstat(solvestat) Lambda(i,1) = lambdaci; Ps(i,:) = Psi'; Pd(i,:) = Pdi'; V(i,:) = Vi'; a(i,:) = ai'; Qg(i,:) = Qgi'; ro(i,:) = roi'; Pij(i,:) = Piji'; Pji(i,:) = Pjii'; lambdac(i,:) = lambdaci; kg(i,:) = kgi; Vc(i,:) = Vci'; ac(i,:) = aci'; Qgc(i,:) = Qgci'; Pijc(i,:) = Pijci'; Pjic(i,:) = Pjici'; NCPi = compNCP(Vi,ai,mV,mFij,mFji); NCP(i,:) = NCPi'; ML(i,1) = ml; % check consistency of the solution (LMP > 0) if modelstat > 3 %min(abs(roi)) < 1e-5 fm_disp('Unfeasible OPF solution. Discarding last solution.') Lambda(end) = []; Ps(end,:) = []; Pd(end,:) = []; V(end,:) = []; a(end,:) = []; Qg(end,:) = []; ro(end,:) = []; Pij(end,:) = []; Pji(end,:) = []; lambdac(end) = []; kg(end) = []; Vc(end,:) = []; ac(end,:) = []; Qgc(end,:) = []; Pijc(end,:) = []; Pjic(end,:) = []; NCP(end,:) = []; ML(end) = []; lambdaci = lambdac(end,:); break end % ------------------------------------------------------ % Bid variations to allow loading parameter increase % % d mu_Pceq_i % D P_i = -sign(P_i) ------------- % d mu_lambda % % where: % % P_i = power bid i % mu_Pceq_i = Lagrangian multiplier of critical PF eq. i % mu_lambda = Lagrangian multiplier of lambda % ------------------------------------------------------ delta = 0.05; while 1 if abs(ml) > 1e-5 deltaPd = ml./mPceq(Demand.bus)/(1+lambdaci); deltaPs = -ml./mPceq(Supply.bus)/(1+lambdaci+kgi); delta_max = norm([deltaPs; deltaPd]); if delta_max == 0, delta_max = 1; end deltaPd = deltaPd/delta_max; deltaPs = deltaPs/delta_max; else deltaPd = zeros(Demand.n,1); deltaPs = zeros(Supply.n,1); end %ml %mPceq %delta_max = max(norm([deltaPs; deltaPd])); %if delta_max == 0, delta_max = 1; end DPs(i,:) = deltaPs'/Settings.mva; DPd(i,:) = deltaPd'/Settings.mva; Pdi = pdbound_demand(Demand,Pd(i,:)' + delta*deltaPd.*Pd(i,:)'); Psi = psbound_supply(Supply,Ps(i,:)' + delta*deltaPs.*Ps(i,:)'); % CPF step % ------------------------------------------------------ if GAMS.basepl PQ = pqreset_pq(PQ,'all'); PV = pvreset_pv(PV,'all'); SW = swreset_sw(SW,'all'); Snapshot(1).Pg = snappg; else PQ = pqzero_pq(PQ,'all'); PV = pvzero_pv(PV,'all'); SW = swzero_sw(SW,'all'); Snapshot(1).Pg = getzeros_bus(Bus); end Demand = pset_demand(Demand,Pdi); pqsum_demand(Demand,1); Supply = pset_supply(Supply,Psi); pgsum_supply(Supply,1); swsum_supply(Supply,1); DAE.y(Bus.a) = aci; DAE.y(Bus.v) = Vci; PV = setvg_pv(PV,'all',DAE.y(PV.vbus)); SW = setvg_sw(SW,'all',DAE.y(SW.vbus)); DAE.x = Snapshot(1).x; Bus.Pg = Bus_old.Pg; Bus.Qg = Bus_old.Qg; Bus.Pl = Bus_old.Pl; Bus.Ql = Bus_old.Ql; % avoid aborting CPF routine due to limits % ------------------------------------------------------ % voltage limits Vbus = DAE.y(Bus.v); idx = find(abs(Vbus-Vmax) < CPF.tolv | Vbus > Vmax); if ~isempty(idx) DAE.y(idx+Bus.n) = Vmax(idx)-1e-6-CPF.tolv; end idx = find(abs(Vbus-Vmin) < CPF.tolv | Vbus < Vmin); if ~isempty(idx) DAE.y(idx+Bus.n) = Vmin(idx)+1e-6+CPF.tolv; end CPF.kg = 0; CPF.lambda = 1; %lambdaci + 1; CPF.linit = 1+lambdaci*0.25; CPF.init = 0; % set contingency for CPF analysis if GAMS.line status = Line.u(GAMS.line); Line = setstatus_line(Line,GAMS.line,0); end % --------------------------------------------- % call continuation power flow routine fm_cpf('gams'); %CPF.lambda = CPF.lambda + 1; % --------------------------------------------- % reset admittance line if GAMS.line Line = setstatus_line(Line,GAMS.line,status); end if isempty(CPF.lambda) fm_disp([' * CPF solution: <empty>']) elseif isnan(CPF.lambda) fm_disp([' * CPF solution: <NaN>']) else fm_disp([' * CPF solution: ',num2str(CPF.lambda-1)]) end if isnan(CPF.lambda) stop_opf = 1; break end if isempty(CPF.lambda) stop_opf = 1; break end if CPF.lambda ~= lambdaci CPF.lambda = CPF.lambda - 0.995; end if CPF.lambda < lambdaci && abs(ml) <= 1e-5 ml = 0; CPF.lambda = lmin+1e-5; end if CPF.lambda < lmin && abs(ml) > 1e-5 fm_disp([' * Decrease Delta Ps and Delta Pd']) delta = 0.5*delta; if delta < 5e-8 fm_disp([' * CPF method cannot find a higher lambda']) stop_opf = 1; break end repeat_cpf = 1; else repeat_cpf = 0; end % maximum lambda increment if (CPF.lambda - lmin) > 0.025 % && (abs(ml) > 1e-5 || CPF.lambda > 0.6) fm_disp(['lambda critical = ',num2str(CPF.lambda)]) fm_disp(['Limit lambda increment to threshold (0.025)']) CPF.lambda = lmin + 0.025; end % stopping criterion % ------------------------------------------------------ if last_point fm_disp('Reached maximum lambda.') if CPF.lambda > lmin fm_disp('Desired maximum lambda is not critical.') end stop_opf = 1; break end if i >= CPF.nump fm_disp('Reached maximum # of continuation steps.') stop_opf = 1; break end if CPF.lambda >= GAMS.lmax CPF.lambda = GAMS.lmax; last_point = 1; end if CPF.lambda == 0 fm_disp('Base case solution is likely unfeasible.') stop_opf = 1; break end if abs(lmin-CPF.lambda) < 1e-5 %fm_disp(['||lambda(i+1) - lambda(i)|| = ', ... % num2str(abs(lmin-CPF.lambda))]) fm_disp('Lambda increment is lower than the desired tolerance.') stop_opf = 1; break elseif ~repeat_cpf if abs(ml) < 1e-5 lmin = CPF.lambda+0.001; lmax = CPF.lambda+0.001; else lmin = CPF.lambda; lmax = CPF.lambda; end break end end %end if stop_opf, break, end end % restore original data and settings % -------------------------------------------------------- DAE.y = Snapshot(1).y; Snapshot(1).Pg = snappg; Bus.Pg = Bus_old.Pg; Bus.Qg = Bus_old.Qg; Bus.Pl = Bus_old.Pl; Bus.Ql = Bus_old.Ql; PV = restore_pv(PV); SW = restore_sw(SW); PQ = pqreset_pq(PQ,'all'); CPF = CPF_old; CPF.init = 4; Varout.t = []; Varout.vars = []; fm_disp % uncomment to plot [dP/d lambda] instead of [P] %Ps = DPs; %Pd = DPd; else fm_disp('Continuation OPF not implemented yet...') cd(currentpath) return end end % ------------------------------------------------------------------- % Output % ------------------------------------------------------------------- MVA = Settings.mva; TPQ = MVA*totp_pq(PQ); % character for backslash bslash = char(92); if GAMS.method == 6, type = 3; end if type == 2 || type == 3 switch GAMS.flow case 0, flow = 'I_'; case 1, flow = 'I_'; case 2, flow = 'P_'; case 3, flow = 'S_'; end Lf = cellstr(num2str(Line.fr)); Lt = cellstr(num2str(Line.to)); TD = MVA*sum(Pd')'; if type == 2 TD = MVA*sum(Pd,2); TTL = TD + TPQ*Ch.val'; TL = MVA*sum(Ps')' + MVA*sum(Bus.Pg)*Ch.val' - TTL; TBL = TL - MVA*Snapshot(1).Ploss*Ch.val'; for i = 1:size(Ps,1) PG(i,:) = full(sparse(1,iBPs,Ps(i,:),1,Bus.n)+Ch.val(i)*Bus.Pg')*MVA; end for i = 1:size(Pd,1) PL(i,:) = full(sparse(1,iBPd,Pd(i,:),1,Bus.n)+Ch.val(i)*Bus.Pl')*MVA; end elseif type == 3 TTL = TD + TPQ; TL = MVA*sum(Ps')' + MVA*sum(Bus.Pg) - TTL; TBL = TL - MVA*Snapshot(1).Ploss; for i = 1:size(Ps,1) PG(i,:) = full(sparse(1,iBPs,Ps(i,:),1,Bus.n)+Bus.Pg')*MVA; end for i = 1:size(Pd,1) PL(i,:) = full(sparse(1,iBPd,Pd(i,:),1,Bus.n)+Bus.Pl')*MVA; end end PayS = -PG.*ro; PayD = PL.*ro; ISO = sum(PayS')'+sum(PayD')'; if GAMS.method == 4 || GAMS.method == 6 MLC = TTL.*(1+lambdac); elseif GAMS.method == 5 MLC = TTL.*lambdac; end Varname.uvars = fm_strjoin('PS_',{Bus.names{Supply.bus}}'); Varname.uvars = [Varname.uvars;fm_strjoin('PD_',{Bus.names{Demand.bus}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('PG_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('PL_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Pay_S_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Pay_D_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('theta_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('V_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Qg_',{Bus.names{iBQg}}')]; if GAMS.method > 2 && GAMS.method ~= 5 Varname.uvars = [Varname.uvars;fm_strjoin('LMP_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('NCP_',{Bus.names{:}}')]; elseif GAMS.method == 2 Varname.uvars = [Varname.uvars;fm_strjoin('LMP_',{Bus.names{:}}')]; elseif GAMS.method == 5 Varname.uvars = [Varname.uvars;fm_strjoin(bslash,'rho_',{Bus.names{:}}')]; else Varname.uvars = [Varname.uvars;{'MCP'}]; end Varname.uvars = [Varname.uvars;fm_strjoin(flow,Lf,'-',Lt)]; Varname.uvars = [Varname.uvars;fm_strjoin(flow,Lt,'-',Lf)]; Varname.uvars = [Varname.uvars;{'Total Demand';'TTL';'Total Losses'; ... 'Total Bid Losses';'IMO Pay'}]; if GAMS.method >= 4 Varname.uvars = [Varname.uvars;{'MLC'}]; Varname.uvars = [Varname.uvars;{'ALC'}]; end Varname.fvars = fm_strjoin('P_{S',{Bus.names{Supply.bus}}','}'); Varname.fvars = [Varname.fvars;fm_strjoin('P_{D',{Bus.names{Demand.bus}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('P_{G',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('P_{L',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Pay_{S',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Pay_{D',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin(bslash,'theta_{',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('V_{',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Q_{g',{Bus.names{iBQg}}','}')]; if GAMS.method > 2 && GAMS.method ~= 5 Varname.fvars = [Varname.fvars;fm_strjoin('LMP_{',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('NCP_{',{Bus.names{:}}','}')]; elseif GAMS.method == 2 Varname.fvars = [Varname.fvars;fm_strjoin('LMP_{',{Bus.names{:}}','}')]; elseif GAMS.method == 5 Varname.fvars = [Varname.fvars;fm_strjoin(bslash,'rho_',{Bus.names{:}}')]; else Varname.fvars = [Varname.fvars;{'MCP'}]; end Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{',Lf,'-',Lt,'}')]; Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{',Lt,'-',Lf,'}')]; Varname.fvars = [Varname.fvars;{'Total Demand';'TTL';'Total Losses'; ... 'Total Bid Losses';'IMO Pay'}]; if GAMS.method >= 4 Varname.fvars = [Varname.fvars;{'MLC'}]; Varname.fvars = [Varname.fvars;{'ALC'}]; end switch GAMS.method case 3 % OPF Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... ro,NCP,Pij,Pji,TD,TTL,TL,TBL,ISO]; case {4,6} % VSC-OPF Varname.uvars = [Varname.uvars;{'lambda_c';'kg_c'}]; Varname.uvars = [Varname.uvars;fm_strjoin('thetac_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Vc_',{Bus.names{:}}')]; Varname.uvars = [Varname.uvars;fm_strjoin('Qgc_',{Bus.names{iBQg}}')]; Varname.uvars = [Varname.uvars;fm_strjoin(flow,'c',Lf,'-',Lt)]; Varname.uvars = [Varname.uvars;fm_strjoin(flow,'c',Lt,'-',Lf)]; Varname.fvars = [Varname.fvars;{[bslash,'lambda_c'];'k_g_c'}]; Varname.fvars = [Varname.fvars;fm_strjoin(bslash,'theta_{c',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('V_{c',{Bus.names{:}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin('Q_{gc',{Bus.names{iBQg}}','}')]; Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{c',Lf,'-',Lt,'}')]; Varname.fvars = [Varname.fvars;fm_strjoin(flow,'{c',Lt,'-',Lf,'}')]; Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... ro,NCP,Pij,Pji,TD,TTL,TL,TBL,ISO,MLC,MLC-TTL,lambdac,kg, ... ac,Vc,Qgc(:,iBQg)*MVA,Pijc,Pjic]; case 5 % MLC Varname.uvars = [Varname.uvars;{'lambda_c';'kg_c'}]; Varname.fvars = [Varname.fvars;{bslash,'lambda_c';'k_g_c'}]; Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... ro,Pij,Pji,TD,TTL,TL,TBL,ISO,MLC,lambdac,kg]; otherwise % SA and MCM Varout.vars = [Ps*MVA,Pd*MVA,PG,PL,PayS,PayD,a,V,Qg(:,iBQg)*MVA, ... MCP,Pij,Pji,TD,TTL,TL,TBL,ISO]; end if GAMS.method == 6 % Continuation OPF Settings.xlabel = [bslash,'lambda (loading parameter)']; Varout.t = Lambda'; elseif type == 2 % Multi Period Auction Varout.vars = Varout.vars([2:end],:); Settings.xlabel = 'hour [h]'; Varout.t = [1:Ypdp.len]'; elseif type == 3 % Pareto Set Single Period Auction Settings.xlabel = [bslash,'omega (weighting factor)']; Varout.t = GAMS.omega'; end Varout.idx = [1:length(Varout.vars(1,:))]; fm_disp(' ---------------------------------------------------------------') fm_disp([' Check file ',Path.psat,'fm_gams.lst for GAMS report.']) if strcmp(control,'6') fm_disp([' PSAT-GAMS Optimization Routine completed in ', ... num2str(etime(clock,initial_time)),' s']) else fm_disp([' PSAT-GAMS Optimization Routine completed in ',num2str(toc),' s']) end Demand = restore_demand(Demand); if ~GAMS.basepl Bus.Pl = buspl; Bus.Ql = busql; PQ = pqreset_pq(PQ,'all'); end if ~GAMS.basepg Snapshot(1).Ploss = ploss; Bus.Pg = buspg; Bus.Qg = busqg; PV = pvreset_pv(PV,'all'); end % restore original bus power injections Bus.Pg = Snapshot(1).Pg; Bus.Qg = Snapshot(1).Qg; Bus.Pl = Snapshot(1).Pl; Bus.Ql = Snapshot(1).Ql; return end if type == 4 Ps = Ps(2,:)'; Pd = Pd(2,:)'; V = V(2,:)'; a = a(2,:)'; Qg = Qg(2,iBQg)'; Pij = Pij(2,:)'; Pji = Pji(2,:)'; if GAMS.method <= 2 MCP = MCP(2,:); end if GAMS.method >= 3 ro = ro(2,:)'; if GAMS.method ~= 5 NCP = NCP(2,:)'; end end if GAMS.method == 4 || GAMS.method == 6 Vc = Vc(2,:)'; ac = ac(2,:)'; Qgc = Qgc(2,iBQg)'; Pijc = Pijc(2,:)'; Pjic = Pjic(2,:)'; end if GAMS.method >= 4 lambdac = lambdac(2); kg = kg(2); end end Demand = pset_demand(Demand,Pd); Supply = pset_supply(Supply,Ps); if GAMS.method == 4 || GAMS.method == 6 DAE.y(Bus.a) = ac; DAE.y(Bus.v) = Vc; Line = gcall_line(Line); glfpc = Line.p; glfqc = Line.q; end if GAMS.method >= 3 DAE.y(Bus.a) = a; DAE.y(Bus.v) = V; Line = gcall_line(Line); Qg = Qg(iBQg); end if GAMS.method == 1 ro = MCP*getones_bus(Bus); end if GAMS.method == 2 [rows,cols] = size(MCP); if rows == 1, ro = MCP'; else ro = MCP; end end Qgmin = Qgmin(iBQg); Qgmax = Qgmax(iBQg); if GAMS.basepl PG = full((sparse(iBPs,1,Ps,Bus.n,1)+Bus.Pg)*MVA); PL = full((sparse(iBPd,1,Pd,Bus.n,1)+Bus.Pl)*MVA); else PG = full(sparse(iBPs,1,Ps,Bus.n,1)*MVA); PL = full(sparse(iBPd,1,Pd,Bus.n,1)*MVA); end QG = full(sparse(iBQg,1,Qg,Bus.n,1)*MVA); QL = full((sparse(iBPd,1,Pd.*tanphi_demand(Demand),Bus.n,1)+Bus.Ql)*MVA); PayS = -ro(Bus.a).*PG; PayD = ro(Bus.a).*PL; ISOPay = -sum(ro(Bus.a).*Line.p*MVA); if (Settings.showlf || GAMS.show) && clpsat.showopf fm_disp fm_disp(' Power Supplies') fm_disp(' ---------------------------------------------------------------') [Psmax,Psmin] = plim_supply(Supply); if GAMS.method == 7 fm_disp({'Bus','Ps','Ps max','Ps min','dPs_up','dPs_dw'}) fm_disp({'<i>','[MW]','[MW]','[MW]','[MW]','[MW]'}) fm_disp([getidx_bus(Bus,Supply.bus),Ps*MVA,Psmax*MVA,Psmin*MVA,dPSup*MVA,dPSdw*MVA]) else fm_disp({'Bus','Ps','Ps max','Ps min'}) fm_disp({'<i>','[MW]','[MW]','[MW]'}) fm_disp([getidx_bus(Bus,Supply.bus),Ps*MVA,Psmax*MVA,Psmin*MVA]) end fm_disp fm_disp(' Power Demands') fm_disp(' ---------------------------------------------------------------') [Pdmax,Pdmin] = plim_demand(Demand); if GAMS.method == 7 fm_disp({'Bus','Pd','Pd max','Pd min','dPd_up','dPd_dw'}) fm_disp({'<i>','[MW]','[MW]','[MW]'}) fm_disp([getidx_bus(Bus,Demand.bus),Pd*MVA,Pdmax*MVA,Pdmin*MVA,dPDup*MVA,dPDdw*MVA]) else fm_disp({'Bus','Pd','Pd max','Pd min'}) fm_disp({'<i>','[MW]','[MW]','[MW]'}) fm_disp([getidx_bus(Bus,Demand.bus),Pd*MVA,Pdmax*MVA,Pdmin*MVA]) end fm_disp fm_disp(' Generator Reactive Powers') fm_disp(' ---------------------------------------------------------------') if GAMS.method == 4 || GAMS.method == 6 fm_disp({'Bus','Qg','Qgc','Qg max','Qg min'}) fm_disp({'<i>','[MVar]','[MVar]','[MVar]','[MVar]'}) fm_disp([getidx_bus(Bus,iBQg),Qg*MVA,Qgc(iBQg)*MVA,Qgmax*MVA,Qgmin*MVA]) else fm_disp({'Bus','Qg','Qg max','Qg min'}) fm_disp({'<i>','[MVar]','[MVar]','[MVar]'}) fm_disp([getidx_bus(Bus,iBQg),Qg*MVA,Qgmax*MVA,Qgmin*MVA]) end fm_disp fm_disp(' Power Flow Solution') fm_disp([' ----------------------------------------------------' ... '-----------']) fm_disp({'Bus','V','theta','PG','PL','QG','QL'}) fm_disp({'<i>','[p.u.]','[rad]','[MW]','[MW]','[MVar]','[MVar]'}) fm_disp([getidx_bus(Bus,0),DAE.y(Bus.v),DAE.y(Bus.a),PG,PL,QG,QL]) fm_disp fm_disp(' Prices and Pays') fm_disp([' ----------------------------------------------------' ... '-----------']) if GAMS.method == 3 || GAMS.method == 4 || GAMS.method == 6 fm_disp({'Bus','LMP','NCP','Pay S','Pay D'}) fm_disp({'<i>','[$/MWh]','[$/MWh]','[$/h]','[$/h]'}) fm_disp([getidx_bus(Bus,0),ro(Bus.a), NCP, PayS, PayD]) else fm_disp({'Bus','LMP','Pay S','Pay D'}) fm_disp({'<i>','[$/MWh]','[$/h]','[$/h]'}) fm_disp([getidx_bus(Bus,0),ro(Bus.a), PayS, PayD]) end if GAMS.method == 4 || GAMS.method == 6 fm_disp fm_disp(' "Critical" Power Flow Solution') fm_disp(' ---------------------------------------------------------------') fm_disp({'Bus','Vc','thetac','PGc','PLc','QGc','QLc'}) fm_disp({'<i>','[p.u.]','[rad]','[MW]','[MW]','[MVar]', ... '[MVar]'}) PG = (1+lambdac+kg)*PG; PL = (1+lambdac)*PL; QL = (1+lambdac)*QL; fm_disp([getidx_bus(Bus,0),Vc,ac,PG,PL,Qgc*MVA,QL]) end fm_disp if GAMS.flow fm_disp(' Flows on Transmission Lines') fm_disp(' ---------------------------------------------------------------') switch GAMS.flow case 1, fm_disp({'From Bus','To Bus','Iij','Iijmax', ... 'Iij margin','Iji','Ijimax','Iji margin'},1) case 2, fm_disp({'From Bus','To Bus','Pij','Pijmax', ... 'Pij margin','Pji','Pjimax','Pji margin'},1) case 3, fm_disp({'From Bus','To Bus','Sij','Sijmax', ... 'Sij margin','Sji','Sjimax','Sji margin'},1) end fm_disp({'<i>','<j>','[p.u.]','[p.u.]', ... '[p.u.]','[p.u.]','[p.u.]','[p.u.]'}) fm_disp([Line.fr, Line.to,Pij, ... L.val(:,5),abs((-abs(Pij)+L.val(:,5))), ... Pji,L.val(:,5),abs((-abs(Pji)+L.val(:,5)))]) fm_disp else fm_disp('Flow limits are disabled.') end if GAMS.method == 4 || GAMS.method == 6 fm_disp(' Flows on Transmission Lines of the "Critical" System') fm_disp(' ---------------------------------------------------------------') switch GAMS.flow case 1, fm_disp({'From Bus','To Bus','Iijc','Iijcmax', ... 'Iijc margin','Ijic','Ijicmax','Ijic margin'}) case 2, fm_disp({'From Bus','To Bus','Pijc','Pijcmax', ... 'Pijc margin','Pjic','Pjicmax','Pjic margin'}) case 3, fm_disp({'From Bus','To Bus','Sijc','Sijcmax', ... 'Sijc margin','Sjic','Sjicmax',['Sjic margin']}) end fm_disp({'<i>','<j>','[p.u.]','[p.u.]', ... '[p.u.]','[p.u.]','[p.u.]','[p.u.]'}) if GAMS.flow fm_disp([Line.fr, Line.to,Pijc, ... L.val(:,5),abs((-abs(Pijc)+L.val(:,5))), ... Pjic,L.val(:,5),abs((-abs(Pjic)+L.val(:,5)))]) fm_disp end end fm_disp fm_disp(' Totals') fm_disp(' ---------------------------------------------------------------') if GAMS.method >= 4, fm_disp([' omega = ',num2str(omega(1))]) fm_disp([' lambda_c = ',num2str(lambdac),' [p.u.]']) fm_disp([' kg = ',num2str(kg),' [p.u.]']) end if GAMS.method == 1 fm_disp([' Market Clearing Price = ',num2str(MCP),' [$/MWh]']) end total_loss = 1e-5*round(sum(Line.p)*1e5)*MVA; bid_loss = 1e-5*round((sum(Line.p)-Snapshot(1).Ploss)*1e5)*MVA; fm_disp([' Total Losses = ',num2str(total_loss),' [MW]']) fm_disp([' Bid Losses = ',num2str(bid_loss),' [MW]']) fm_disp([' Total demand = ',num2str(sum(Pd)*MVA),' [MW]']) fm_disp([' Total Transaction Level = ', ... fvar(sum(Pd)*MVA+TPQ,8),' [MW]']); if GAMS.method == 4 || GAMS.method == 6 fm_disp([' Maximum Loading Condition = ', ... fvar((1+lambdac)*(sum(Pd)*MVA+TPQ),8),' [MW]']); fm_disp([' Available Loading Capability = ', ... fvar(lambdac*(sum(Pd)*MVA+TPQ),8),' [MW]']); end if GAMS.method == 5 fm_disp([' Maximum Loading Condition = ', ... fvar(lambdac*(sum(Pd)*MVA+TPQ),8),' [MW]']); end fm_disp([' IMO Pay = ',num2str(ISOPay),' [$/h]']); fm_disp end fm_disp(' ---------------------------------------------------------------') fm_disp([' Check file ',Path.psat,'fm_gams.lst for GAMS report.']) gams_mstat(modelstat) gams_sstat(solvestat) if strcmp(control,'6') fm_disp([' PSAT-GAMS Optimization Routine completed in ', ... num2str(etime(clock,initial_time)),' s']) else fm_disp([' PSAT-GAMS Optimization Routine completed in ',num2str(toc),' s']) end if noDem, Demand = restore_demand(Demand); end if ~GAMS.basepl Bus.Pl = buspl; Bus.Ql = busql; PQ = pqreset_pq(PQ,'all'); end if ~GAMS.basepg Snapshot(1).Ploss = ploss; Bus.Pg = buspg; Bus.Qg = busqg; PV = pvreset_pv(PV,'all'); end % restore original bus power injections Bus.Pg = Snapshot(1).Pg; Bus.Qg = Snapshot(1).Qg; Bus.Pl = Snapshot(1).Pl; Bus.Ql = Snapshot(1).Ql; % =============================================================== function [Pij,Pji,Qg] = updatePF(Pd,Ps,iBQg) % Power FLow Solution with the current simple auction solution % =============================================================== global Settings Bus Line PQ PV SW Demand Supply GAMS Busold = Bus; Demand = pset_demand(Demand,Pd); Supply = pset_supply(Supply,Ps); pg = SW.pg; pqsum_demand(Demand,1); pgsum_supply(Supply,1); show_old = Settings.show; Settings.show = 0; Settings.locksnap = 1; fm_spf Settings.locksnap = 0; Settings.show = show_old; [Pij,Pji] = flows_line(Line,max(GAMS.flow,1)); Qg = Bus.Qg(iBQg); Bus = Busold; SW = setpg_sw(SW,'all',pg); PQ = restore_pq(PQ); PV = pvreset_pv(PV,'all'); % ========================================================================== function NCP = compNCP(V,a,mV,mFij,mFji) % Nodal Congestion Prices % ========================================================================== global DAE SW GAMS Line Bus yold = DAE.y; Gyold = DAE.Gy; DAE.y(Bus.a) = a; DAE.y(Bus.v) = V; Gycall_line(Line) fm_setgy(SW.refbus) [Fij,Jij,Fji,Jji] = fjh2_line(Line,max(GAMS.flow,1)); dH_dtV = Jij'*mFij + Jji'*mFji + [getzeros_bus(Bus);mV]; dH_dtV(SW.refbus,:) = 0; NCP = DAE.Gy'\dH_dtV; NCP = NCP(Bus.a); DAE.y = yold; DAE.Gy = Gyold; % ========================================================================== function varargout = psatgams(varargin) % PSAT-GAMS interface % ========================================================================== global Settings Path % writing GAMS input data %--------------------------------------------------------------------- fid1 = fopen('psatglobs.gms','wt+'); fid2 = fopen('psatdata.gms','wt+'); fprintf(fid2,'%s\n','$onempty'); for i = 2:nargin if ischar(varargin{i}) fprintf(fid1,'$setglobal %s ''%s''\n',inputname(i), ... varargin{i}); elseif isnumeric(varargin{i}) fprintf(fid2,'$kill %s\n',inputname(i)); if length(varargin{i}) == 1 fprintf(fid2,'scalar %s /%f/;\n',inputname(i),varargin{i}); else fprintf(fid2,'parameter %s /\n',inputname(i)); [x,y,v] = find(varargin{i}); fprintf(fid2,'%d.%d %f\n',[x y v]'); fprintf(fid2,'/;\n'); end elseif isstruct(varargin{i}) labels = varargin{i}.labels; fprintf(fid2,'$kill %s\n',varargin{i}.name); fprintf(fid2,'parameter %s /\n',varargin{i}.name); [x,y,v] = find(varargin{i}.val); if iscell(labels{1}) %a = fm_strjoin(labels{1}(x),'.',labels{2}(y)',[blanks(length(x))',num2str(v)]); %fprintf(fid2,'%s\n',a{:}); for j = 1:length(x) fprintf(fid2,'%s.%s %f\n',labels{1}{x(j)},labels{2}{y(j)},v(j)); end else for j = 1:length(x) fprintf(fid2,'%s %f\n',labels{y(j)},v(j)); end end fprintf(fid2,'/;\n'); end end fprintf(fid2,'%s\n','$offempty'); fclose(fid1); fclose(fid2); % Lauching GAMS %--------------------------------------------------------------------- status = 0; t0 = clock; %disp(['gams ',varargin{1},' -error=PSAT']) [status,result] = system(['gams ',varargin{1}]); fm_disp([' GAMS routine completed in ',num2str(etime(clock,t0)),' s']) if status fm_disp(result) return end % Reading GAMS output %--------------------------------------------------------------------- nout = 0; EPS = eps; clear psatsol psatsol if nout < nargout for i = nout+1:nargout varargout{i} = []; end end if nout > nargout varargout(nargout+1:nout) = []; end %--------------------------------------------------------------------- function gams_mstat(status) if isempty(status), return, end switch status case 0, fm_disp(' GAMS model status: not available') case 1, fm_disp(' GAMS model status: optimal') case 2, fm_disp(' GAMS model status: locally optimal') case 3, fm_disp(' GAMS model status: unbounded') case 4, fm_disp(' GAMS model status: infeasible') case 5, fm_disp(' GAMS model status: locally infeasible') case 6, fm_disp(' GAMS model status: intermediate infeasible') case 7, fm_disp(' GAMS model status: intermediate non-optimal') case 8, fm_disp(' GAMS model status: integer solution') case 9, fm_disp(' GAMS model status: intermediate non-integer') case 10, fm_disp(' GAMS model status: integer infeasible') case 11, fm_disp(' GAMS model status: ???') case 12, fm_disp(' GAMS model status: error unknown') case 13, fm_disp(' GAMS model status: error no solution') otherwise, fm_disp(' GAMS model status: unknown model status') end %--------------------------------------------------------------------- function gams_sstat(status) if isempty(status), return, end switch status case 0, fm_disp(' GAMS solver status: not available') case 1, fm_disp(' GAMS solver status: normal completion') case 2, fm_disp(' GAMS solver status: iteration interrupt') case 3, fm_disp(' GAMS solver status: resource interrupt') case 4, fm_disp(' GAMS solver status: terminated by solver') case 5, fm_disp(' GAMS solver status: evaluation error limit') case 6, fm_disp(' GAMS solver status: unknown') case 7, fm_disp(' GAMS solver status: ???') case 8, fm_disp(' GAMS solver status: error preprocessor error') case 9, fm_disp(' GAMS solver status: error setup failure') case 10, fm_disp(' GAMS solver status: error solver failure') case 11, fm_disp(' GAMS solver status: error internal solver error') case 12, fm_disp(' GAMS solver status: error post-processor error') case 13, fm_disp(' GAMS solver status: error system failure') otherwise, fm_disp(' GAMS solver status: unknown solver status') end
github
Sinan81/PSAT-master
fm_build.m
.m
PSAT-master/psat-oct/psat/fm_build.m
25,468
utf_8
688cdaed0380b34975aab856abfbaf9e
function fm_build %FM_BUILD build new component functions (Symbolic Toolbox is needed) % %FM_BUILD % %see also FM_MAKE FM_COMPONENT % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 19-Dec-2003 %Version: 1.0.1 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Comp Settings Fig Path global Algeb Buses Initl Param Servc State % *********************************************************************** % some control variables error_v = []; lasterr(''); null = '0'; % useful strings c_name = Comp.name; c_name(1) = upper(c_name(1)); % variable arrays state_vect = varvect(State.name, ' '); algeb_vect = varvect(Algeb.name, ' '); param_vect = varvect(Param.name, ' '); initl_vect = varvect(Initl.name, ' '); servc_vect = varvect(Servc.name, ' '); pq_Servc = 0; % equation arrays servc_eq = varvect(Servc.eq,'; '); state_eq = varvect(State.eq,'; '); algeb_eq = varvect(Algeb.eq,'; '); % ******************************************************************************** % check equations if State.neq > 0 state_check = strmatch('null',State.eq,'exact'); if state_check error_v = [error_v; ... fm_strjoin('Differential equation for "', ... State.eqidx(state_check), ... '" has not been defined.')]; end end if Servc.neq > 0 servc_foo = fm_strjoin(Servc.type,Servc.eq); servc_check = strmatch('Innernull',servc_foo,'exact'); servc_check = [servc_check; strmatch('Outputnull',servc_foo,'exact')]; if servc_check error_v = [error_v; ... fm_strjoin('Service equation for "', ... Servc.eqidx(servc_check), ... '" has not been defined.')]; end end % ******************************************************************************** % check variable usage servc_idx = [strmatch('Inner',Servc.type); strmatch('Output',Servc.type)]; total_var = [State.name; Algeb.name; Servc.eqidx(servc_idx); Param.name; Initl.name]; total_eqn = [' ',servc_eq,' ',state_eq,' ',algeb_eq,' ',varvect(State.time,'*'),' ']; for i = 1:length(total_var) idx = findstr(total_eqn,total_var{i}); if isempty(idx) error_v{end+1,1} = ['The variable "',total_var{i},'" is not used in any equation.']; else before = total_eqn(idx-1); after = total_eqn(idx+length(total_var{i})); check = 1; for j = 1:length(idx) a = double(after(j)); b = double(before(j)); a1 = ~isletter(after(j)); a2 = (a ~= 95); a3 = (a > 57 || a < 48); b1 = ~isletter(before(j)); b2 = (b ~= 95); b3 = (b > 57 || b < 48); if a1 && a2 && a3 && b1 && b2 && b3, check = 0; break, end end if check error_v{end+1,1} = ['The variable "',total_var{i}, ... '" is not used in any equation.']; end end end % ******************************************************************************** % symbolic variables try if state_vect, eval(['syms ',state_vect]), end if algeb_vect, eval(['syms ',algeb_vect]), end if param_vect, eval(['syms ',param_vect]), end if servc_vect, eval(['syms ',servc_vect]), end if initl_vect, eval(['syms ',initl_vect]), end % compute Jacobians matrices (Maple Symbolic Toolbox) if ~isempty(state_eq) if ~isempty(state_vect) eval(['Fx = jacobian([',state_eq, '],[', state_vect, ']);']); end if ~isempty(algeb_vect) eval(['Fy = jacobian([',state_eq, '],[', algeb_vect, ']);']); end if ~isempty(servc_vect) eval(['Fz = jacobian([',state_eq, '],[', servc_vect, ']);']); end if pq_Servc eval(['Fpq = jacobian([',state_eq, '],[', pq_vect, ']);']); end end if ~isempty(algeb_eq) if ~isempty(state_vect) eval(['Gx = jacobian([',algeb_eq, '],[', state_vect, ']);']); end if ~isempty(algeb_vect) eval(['Gy = jacobian([',algeb_eq, '],[', algeb_vect, ']);']); end if ~isempty(servc_vect) eval(['Gz = jacobian([',algeb_eq, '],[', servc_vect, ']);']); end if pq_Servc eval(['Gpq = jacobian([',alg_eqeb, '],[', pq_vect, ']);']); end end if ~isempty(servc_eq) if ~isempty(state_vect) eval(['Zx = jacobian([',servc_eq, '],[', state_vect, ']);']); end if ~isempty(algeb_vect) eval(['Zy = jacobian([',servc_eq, '],[', algeb_vect, ']);']); end if ~isempty(servc_vect) eval(['Zz = jacobian([',servc_eq, '],[', servc_vect, ']);']); end if pq_Servc eval(['Zpq = jacobian([',servc_eq, '],[', pq_vect, ']);']); end end end % ******************************************************************************** % check synthax of equations for i = 1:State.neq try eval([State.eq{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In differential equation "', ... State.eq{i,1}, '")']; end try eval([State.init{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In state variable "', ... State.name{i,1}, '" initialization expression)']; end state_init{i,1} = vectorize(State.init{i,1}); end for i = 1:Algeb.neq try eval([Algeb.eq{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In algebraic equation "', ... State.eq{i,1}, '")']; end end for j = 1:Servc.neq try eval([Servc.eq{i,1},';']) catch error_v{end+1,1} = [lasterr, ' (In service equation "', ... Servc.eqidx{i,1}, '")']; end end % check component name if isempty(Comp.name) error_v{end+1,1} = 'Component name is empty.'; return end % ******************************************************************************** % display errors if ~isempty(error_v) error_v = fm_strjoin('Error#',num2str([1:length(error_v)]'),': ',error_v); error_v = [{['REPORT OF ERRORS ENCOUNTERED WHILE BUILDING ', ... 'NEW COMPONENT "',Comp.name,'.m"']}; error_v]; error_v{end+1,1} = ['BUILDING NEW COMPONENT FILE "', ... Comp.name,'.m" FAILED']; fm_disp fm_disp(error_v{1:end-1}) fm_disp(['BUILDING NEW COMPONENT FILE "',Comp.name,'.m" FAILED']) fm_update set(findobj(Fig.update,'Tag','Listbox1'),'String',error_v, ... 'BackgroundColor','w', ... 'ForegroundColor','r', ... 'Enable','inactive', ... 'max',2, ... 'Value',[]); set(findobj(Fig.update,'Tag','Pushbutton2'),'Enable','off'); return end % *********************************************************************** % check for previous versions a = what(Path.psat); olderfile = strmatch(['fm_',Comp.name,'.m'],a.m,'exact'); if ~isempty(olderfile) uiwait(fm_choice(['Overwrite Existing File "fm_',Comp.name,'.m" ?'])); if ~Settings.ok, return, end end % *********************************************************************** % open new component file fid = fopen([Path.psat, 'fm_', Comp.name,'.m'], 'wt'); if fid == -1 fm_disp(['Cannot open file fm_',Comp.name,'. Check permissions']) return end fprintf(fid, ['function fm_', Comp.name, '(flag)']); % write help of the function if isempty(Comp.descr) Comp.descr = ['Algebraic Differential Equation ', ... Comp.name, '.m']; end fprintf(fid, ['\n\n%%FM_', upper(Comp.name),' defines ',Comp.descr]); % ******************************************************************** % data format .con fprintf(fid, ['\n%%\n%%Data Format ', c_name, '.con:']); fprintf(fid, '\n%% col #%d: Bus %d number',[1:Buses.n;1:Buses.n]); idx_inn = strmatch('Inner', Servc.type, 'exact'); idx_inp = strmatch('Input', Servc.type, 'exact'); idx_out = strmatch('Output', Servc.type, 'exact'); fprintf(fid, '\n%% col #%d: Power rate [MVA]',Buses.n+1); fprintf(fid, '\n%% col #%d: Bus %d Voltage Rate [kV]', ... [Buses.n+1+[1:Buses.n];1:Buses.n]); fprintf(fid, '\n%% col #%d: Frequency rate [Hz]',2*Buses.n+2); inip = 2*Buses.n+3; endp = 2*Buses.n+2+Param.n; pidx = inip:endp; for i=1:length(pidx) fprintf(fid, '\n%% col #%d: %s %s [%s]', ... pidx(i),Param.name{i},Param.descr{i},Param.unit{i}); end x_max = [1:State.n]; if State.n x_idx = strmatch('None',State.limit(:,1),'exact'); x_max(x_idx) = []; end x_min = [1:State.n]; if State.n x_idx = strmatch('None',State.limit(:,2),'exact'); x_min(x_idx) = []; end n_xmax = length(x_max); n_xmin = length(x_min); for i=1:n_xmax fprintf(fid,'\n%% col #%d: %s',endp+i, ... State.limit{x_max(i),1}); end for i=1:n_xmin fprintf(fid,'\n%% col #%d: %s',endp+n_xmax+i, ... State.limit{x_min(i),1}); end s_max = [1:Servc.neq]; if Servc.n s_idx = strmatch('None',Servc.limit(:,1),'exact'); s_max(s_idx) = []; end s_min = [1:Servc.neq]; if Servc.n s_idx = strmatch('None',Servc.limit(:,2),'exact'); s_min(s_idx) = []; end n_smax = length(s_max); n_smin = length(s_min); for i=1:n_smax fprintf(fid,'\n%% col #%d: %s', ... endp+n_xmax+n_xmin+i,Servc.limit{s_max(i),1}); end for i=1:n_smin fprintf(fid,'\n%% col #%d: %s', ... endp+n_xmax+n_xmin+n_smax+i,Servc.limit{s_min(i),1}); end okdata = 0; nidx = 0; if ~isempty(idx_inn) || ~isempty(idx_out) okdata = 1; end if Initl.n || okdata fprintf(fid, ['\n%% \n%%Data Structure: ', c_name, '.dat:']); end for i=1:Initl.n fprintf(fid,'\n%% col #%d: %s', i,Initl.name{i}); end if okdata nidx = length(idx_inn)+length(idx_out); iidx = [idx_inn;idx_out]; for i=1:nidx fprintf(fid,'\n%% col #%d: %s', ... Initl.n+i,Servc.eqidx{iidx(i)}); end end % function calls fprintf(fid, ['\n%% \n%%FM_', upper(Comp.name),'(FLAG)']); if Comp.init fprintf(fid, ['\n%% FLAG = 0 -> initialization']); end if ~isempty(algeb_eq) fprintf(fid, ['\n%% FLAG = 1 -> algebraic equations']); fprintf(fid, ['\n%% FLAG = 2 -> algebraic Jacobians']); end if ~isempty(state_eq); fprintf(fid, ['\n%% FLAG = 3 -> differential equations']); fprintf(fid, ['\n%% FLAG = 4 -> state Jacobians']); end if n_xmax || n_xmin > 0 fprintf(fid, ['\n%% FLAG = 5 -> non-windup limiters)']); end fprintf(fid, '\n%% \n%%Author: File automatically generated by PSAT'); fprintf(fid, '\n%%Date: %s',date); % global variables fprintf(fid, ['\n\nglobal ',c_name,' DAE Bus Settings']); % ************************************************************************ % general settings fprintf(fid, '\n'); for i=1:State.n fprintf(fid,'\n%s = DAE.x(%s.%s);',State.name{i},c_name, ... State.name{i}); end if Algeb.n idx_v = strmatch('V',Algeb.name); idx_a = strmatch('t',Algeb.name); if idx_v num_v = strrep(Algeb.name(idx_v),'V',''); if Buses.n == 1 fprintf(fid,'\n%s = DAE.y(%s.bus+Bus.n);', ... Algeb.name{idx_v},c_name); else for i=1:length(idx_v) fprintf(fid,'\n%s = DAE.y(%s.bus%s+Bus.n);', ... Algeb.name{idx_v(i)},c_name,num_v{i}); end end end if idx_a num_a = strrep(Algeb.name(idx_a),'theta',''); if Buses.n == 1 fprintf(fid,'\n%s = DAE.y(%s.bus);', ... Algeb.name{idx_a},c_name); else for i=1:length(idx_a) fprintf(fid,'\n%s = DAE.y(%s.bus%s);', ... Algeb.name{idx_a(i)},c_name,num_a{i}); end end end end for i=1:Param.n fprintf(fid,'\n%s = %s.con(:,%d);',Param.name{i},c_name,pidx(i)); end for i=1:n_xmax, fprintf(fid,'\n%s = %s.con(:,%d);',State.limit{x_max(i),1}, ... c_name,endp+i); end for i=1:n_xmin, fprintf(fid,'\n%s = %s.con(:,%d);',State.limit{x_min(i),2}, ... c_name,endp+n_xmax+i); end for i=1:n_smax, fprintf(fid,'\n%s = %s.con(:,%d);',Servc.limit{s_max(i),1}, ... c_name,endp+n_xmax+n_xmin+i); end for i=1:n_smin, fprintf(fid,'\n%s = %s.con(:,%d);',Servc.limit{s_min(i),2}, ... c_name,endp+n_xmax+n_xmin+n_smax+i); end for i=1:Initl.n, fprintf(fid,'\n%s = %s.dat(:,%d);',Initl.name{i},c_name,i); end for i=1:nidx, fprintf(fid,'\n%s = %s.dat(:,%d);',Servc.eqidx{iidx(i)},c_name, ... Initl.n+i); end % ********************************************************************** % initialization if Comp.init fprintf(fid, '\n\nswitch flag\n case 0 %% initialization'); msg = ['Component']; idx_T = [1:State.n]; idx = strmatch('None',State.time,'exact'); idx_T(idx) = []; if idx_T fprintf(fid,'\n\n %%check time constants'); end for i=1:length(idx_T), fprintf(fid,['\n idx = find(%s == 0);\n if idx\n ', ... Comp.name,'warn(idx, ''Time constant %s ', ... 'cannot be zero. %s = 0.001 s will be used.''),\n ' ... 'end'],State.time{idx_T(i)}, ... State.time{idx_T(i)},State.time{idx_T(i)}); fprintf(fid,'\n %s.con(idx,%d) = 0.001;', ... c_name,pidx(strmatch(State.time{idx_T(i)}, ... Param.name,'exact'))); end fprintf(fid,'\n\n %%variable initialization'); for i=1:State.n, fprintf(fid,'\n DAE.x(%s.%s) = %s;',c_name,State.name{i},state_init{i}); fprintf(fid,'\n %s = DAE.x(%s.%s);',State.name{i},c_name,State.name{i}); end for i=1:nidx, fprintf(fid,'\n %s.dat(:,%d) = %s;',Initl.n+i,c_name,vectorize(Servc.eq{i})); fprintf(fid,'\n %s = %s.dat(:,%d);',Servc.eqidx{iidx(i)},c_name,Initl.n+i); end for i=1:Initl.n fprintf(fid,'\n %s.dat(:,%d) = %s;',c_name,i, ... strrep(Initl.name{i},'_0','')); end fprintf(fid,'\n\n %%check limits'); for i=1:n_xmax fprintf(fid,['\n idx = find(%s > %s_max); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is over its maximum limit.''), end'], ... State.name{x_max(i)},State.name{x_max(i)}, ... State.name{x_max(i)}); end for i=1:n_xmin fprintf(fid,['\n idx = find(%s < %s_min); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is under its minimum limit.''), end'], ... State.name{x_min(i)},State.name{x_min(i)}, ... State.name{x_min(i)}); end for i=1:n_smax fprintf(fid,['\n idx = find(%s > %s_max); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is over its maximum limit.''), end'], ... Servc.name{s_max(i)},Servc.name{s_max(i)}, ... Servc.name{s_max(i)}); end for i=1:n_smin fprintf(fid,['\n idx = find(%s < %s_min); if idx, ', ... Comp.name,'warn(idx, '' State variable %s ', ... 'is under its minimum limit.''), end'], ... Servc.name{s_min(i)},Servc.name{s_min(i)}, ... Servc.name{s_min(i)}); end fprintf(fid,['\n fm_disp(''Initialization of ',c_name, ... 'components completed.'')\n']); end % ********************************************************************** % algebraic equations if ~isempty(algeb_eq) if Comp.init fprintf(fid, '\n case 1 %% algebraic equations\n'); else fprintf(fid, '\n\nswitch flag\n case 1 %% algebraic equations\n'); end end aidx = [1:Algeb.neq]; idx = strmatch('null',Algeb.eq); aidx(idx) = []; idx = strmatch('0',Algeb.eq); aidx(idx) = []; for i = 1:length(aidx) if Buses.n == 1 a1 = ''; else a1 = num2str(ceil(aidx(i)/2)); end if rem(aidx(i),2) fprintf(fid,'\n DAE.g = DAE.g + sparse(%s.bus%s,1,%s,DAE.m,1);', ... c_name,a1,vectorize(Algeb.eq{aidx(i)})); else fprintf(fid,'\n DAE.g = DAE.g + sparse(%s.bus%s+Bus.n,1,%s,DAE.m,1);', ... c_name,a1,vectorize(Algeb.eq{aidx(i)})); end end % ******************************************************************** % algebraic Jacobians % substitution of inner service variables for j = 1:5 for i = 1:Servc.neq if strcmp(Servc.type{i},'Inner') && ~strcmp(Servc.eq{i},'null') state_eq = strrep(state_eq,Servc.eqidx{i},['(',Servc.eq{i},')']); algeb_eq = strrep(algeb_eq,Servc.eqidx{i},['(',Servc.eq{i},')']); servc_eq = strrep(servc_eq,Servc.eqidx{i},['(',Servc.eq{i},')']); end end end if ~isempty(algeb_eq) fprintf(fid, '\n\n case 2 %% algebraic Jacobians\n'); end eqformat = '\n DAE.J%d%d = DAE.J%d%d + sparse(%s.bus%s,%s.bus%s,%s,Bus.n,Bus.n);'; for j = 1:length(aidx) i = aidx(j); a1 = 2-rem(i,2); if Buses.n == 1 a2 = ''; else a2 = num2str(ceil(i/2)); end for h = 1:Algeb.n type = Algeb.name{h,1}; if strcmp(type(1), 'V'); a3 = 2; if Buses.n == 1 a4 = ''; else a4 = type(2:length(type)); end elseif strcmp(type(1:5), 'theta'); a3 = 1; if Buses.n == 1 a4 = ''; else a4 = type(6:length(type)); end end if ~strcmp(char(Gy(i,h)),'0') fprintf(fid,eqformat,a1,a3,a1,a3,c_name,a2,c_name,a4, ... vectorize(char(Gy(i,h)))); end end end % check limits in case of state variable dependancies Temp = 0; for i = 1:Servc.neq; Temp = ~strcmp(Servc.limit{i},'None'); break; end S = 0; if Temp for i = 1:Servc.neq; S = ~strcmp(Servc.type{i},'Input'); break; end end if S fprintf(fid,'\n'); for i = 1:length(Servc.eqidx) s_var = Servc.eqidx{i}; for k = 1:Servc.neq; if strcmp(s_var,Servc.name{k}); break; end; end if ~strcmp(Servc.type{k},'Input') && ~isempty(findstr(algeb_eq,s_var)) a = strcmp(Servc.limit{k,1},'None'); b = strcmp(Servc.limit{k,2},'None'); if ~a || ~b fprintf(fid, ['\n if (']); if ~a fprintf(fid,[Servc.name{k},'(i) <= ',Servc.name{k},'_max(i)']); else fprintf(fid,'('); end if ~a && ~b fprintf(fid,' || '); end if ~b fprintf(fid,[Servc.name{k},'(i) >= ',Servc.name{k},'_min(i))']); else fprintf(fid,')'); end fprintf(fid,'\n end'); end end end end % ********************************************************************* % differential & service equations if ~isempty(state_eq) if Comp.init || ~isempty(algeb_eq) fprintf(fid, '\n\n case 3 %% differential equations\n'); else fprintf(fid, '\n\nswitch flag\n case 3 %% differential equations\n'); end end for i = 1:Servc.neq Temp = Servc.type{i}; if strcmp(Temp,'Inner') s_eq = vectorize(Servc.eq{i}); fprintf(fid,['\n ',Servc.name{i},' = ',s_eq,';']); if ~strcmp(Servc.limit{i,1},'None') fprintf(fid, ['\n ',Servc.name{i}, ... ' = min(',Servc.name{i},',',Servc.name{i},'_max);']); end if ~strcmp(Servc.limit{i,2},'None') fprintf(fid, ['\n ',Servc.name{i}, ... ' = max(',Servc.name{i},',',Servc.name{i},'_min);']); end end end for i = 1:State.n if strcmp(State.nodyn{i},'Yes') fprintf(fid, ['\n no_dyn_',State.name{i},' = find(',State.time{i},' == 0);']); fprintf(fid, ['\n ', State.time{i}, '(no_dyn_',State.name{i},') = 1;']); end if strcmp(State.time{i},'None') s_eq = vectorize(State.eq{i}); else s_eq = vectorize(['(',State.eq{i},')/',State.time{i}]); end fprintf(fid, ['\n DAE.f(',c_name,'.',State.name{i},') = ',s_eq,';']); if strcmp(State.nodyn{i},'Yes') fprintf(fid, ['\n DAE.f(',c_name,'.',State.name{i},'(no_dyn_',State.name{i},')) = 0;']); end end if State.n > 0; if strcmp(State.nodyn{State.n},'Yes'); fprintf(fid, '\n'); end; end % set hard limits fprintf(fid,'\n %% non-windoup limits'); limfor1 = '\n idx = find(%s >= %s_max && DAE.f(%s) > 0);'; limfor2 = '\n if idx, DAE.f(%s(idx)) = 0; end'; limfor3 = '\n DAE.x(%s) = min(%s,%s_max);'; limfor4 = '\n idx = find(%s <= %s_min && DAE.f(%s) < 0);'; limfor5 = '\n DAE.x(%s) = max(%s,%s_min);'; for i = 1:State.n varidx = [c_name,'.',State.name{i}]; a = strcmp(State.limit{i,1},'None'); if ~a fprintf(fid,limfor1,State.name{i},State.name{i},varidx); fprintf(fid,limfor2,State.name{i}); fprintf(fid,limfor3,varidx,State.name{i},State.name{i}); end b = strcmp(State.limit{i,2},'None'); if ~b fprintf(fid,limfor4,State.name{i},State.name{i},varidx); fprintf(fid,limfor2,State.name{i}); fprintf(fid,limfor5,varidx,State.name{i},State.name{i}); end end fprintf(fid, '\n'); numdata = Initl.n; for i = 1:Servc.neq Temp = Servc.type{i}; if okdata && strcmp(Temp,'Inner') numdata = numdata + 1; fprintf(fid,['\n ',c_name,'.dat(:,',int2str(numdata),') = ', Servc.name{i},';']); elseif strcmp(Temp,'Output') numdata = numdata + 1; s_eq = vectorize(Servc.eq{i}); TempT = [c_name,'.dat(:,',int2str(numdata),')']; fprintf(fid,['\n ',TempT,' = ',s_eq,';']); zz = ['z(',Servc.name{i},'_',Comp.name,'_idx)']; if ~strcmp(Servc.limit{i,1},'None') fprintf(fid, ['\n ',TempT,' = min(',TempT,',',Servc.name{i},'_max);']); end if ~strcmp(Servc.limit{i,2},'None') fprintf(fid, ['\n ',TempT,' = max(',TempT,',',Servc.name{i},'_min);']); end fprintf(fid,['\n ',zz,' = ',zz,' + ',TempT,';']); end end fprintf(fid, '\n'); % ********************************************************************* % state variable Jacobians if ~isempty(state_eq) fprintf(fid, '\n\n case 4 %% state variable Jacobians\n'); end % DAE.Fx for j = 1:State.n if strcmp(State.nodyn{j},'Yes') fprintf(fid, ['\n no_dyn_',State.name{j},' = find(',State.time{j},' == 0);']); fprintf(fid, ['\n ', State.time{j}, '(no_dyn_',State.name{j},') = 1;']); end end fprintf(fid, '\n'); if State.n, fprintf(fid,'\n %% DAE.Fx'); end fxformat = '\n DAE.Fx = DAE.Fx + sparse(%s,%s,%s,DAE.n,DAE.n);'; for j = 1:State.n x_idx1 = [c_name,'.',State.name{j}]; for i = 1:State.n x_idx2 = [c_name,'.',State.name{i}]; if strcmp(State.time{j},'None') && ~strcmp(char(Fx(j,i)),'0') fxexp = vectorize(char(Fx(j,i))); else fxexp = ['(',vectorize(char(Fx(j,i))),')./',State.time{j}]; end if ~strcmp(fxexp,['(0)./',State.time{j}]) fprintf(fid,fxformat,x_idx1,x_idx2,fxexp); end end end fprintf(fid,'\n'); % DAE.Fy if State.n && Algeb.n, fprintf(fid,'\n %% DAE.Fy'); end fyformat = '\n DAE.Fy = DAE.Fy + sparse(%s,%s,%s,DAE.n,DAE.m);'; for j = 1:State.n x_idx1 = [c_name,'.',State.name{j}]; for i = 1:Algeb.n type = Algeb.name{i}; if strcmp(type(1),'V') if Buses.n == 1 x_idx2 = [c_name,'.bus','','+Bus.n']; else x_idx2 = [c_name,'.bus',type(2:length(type)),'+Bus.n']; end elseif strcmp(type(1:5),'theta') if Buses.n == 1 x_idx2 = [c_name,'.bus','']; else x_idx2 = [c_name,'.bus',type(6:length(type))]; end end if strcmp(State.time{j},'None') && ~strcmp(char(Fy(j,i)),'0') fyexp = vectorize(char(Fy(j,i))); else fyexp = ['(',vectorize(char(Fy(j,i))),')./',State.time{j}]; end if ~strcmp(fyexp,['(0)./',State.time{j}]) fprintf(fid,fyformat,x_idx1,x_idx2,fyexp); end end end fprintf(fid,'\n'); % DAE.Gx if State.n && Algeb.n, fprintf(fid,'\n %% DAE.Gx'); end gxformat = '\n DAE.Gx = DAE.Gx + sparse(%s,%s,%s,DAE.m,DAE.n);'; for j = 1:Algeb.neq if ~strcmp(Algeb.eq{1},'null') type = Algeb.eqidx{j,1}; if strcmp(type(1),'P') if Buses.n == 1 a_idx = [c_name,'.bus','']; else a_idx = [c_name,'.bus',type(2:length(type))]; end elseif strcmp(type(1),'Q') if Buses.n == 1 a_idx = [c_name,'.bus','','+Bus.n']; else a_idx = [c_name,'.bus',type(2:length(type)),'+Bus.n']; end end for h = 1:State.n x_idx = [c_name,'.',State.name{h}]; algexp = vectorize(char(Gx(j,h))); if ~strcmp(algexp,'0') fprintf(fid,gxformat,a_idx,x_idx,algexp); end end end end %if State.n > 0, fprintf(fid, ['\n\n end']); end % *************************************************************** % non-windup limiters if n_xmax || n_xmin fprintf(fid, '\n\n case 5 %% non-windup limiters\n'); for i = 1:State.n M = ~strcmp(State.limit{i,1},'None'); m = ~strcmp(State.limit{i,2},'None'); if M || m fprintf(fid, ['\n idx = find((']); if M, fprintf(fid,'%s >= %s_max',State.name{i},State.name{i}); end if M && m; fprintf(fid,' || '); end if m, fprintf(fid,'%s <= %s_min',State.name{i},State.name{i}); end fprintf(fid,[') && DAE.f(',c_name,'.%s) == 0);'],State.name{i}); fprintf(fid, '\n if ~isempty(idx)'); fprintf(fid,['\n k = ',c_name,'.%s(idx);'],State.name{i}); fprintf(fid,['\n DAE.tn(k) = 0;']); fprintf(fid,['\n DAE.Ac(:,k) = 0;']); fprintf(fid,['\n DAE.Ac(k,:) = 0;']); fprintf(fid,['\n DAE.Ac = DAE.Ac - sparse(k,k,1,DAE.m+DAE.n,DAE.m+DAE.n);']); fprintf(fid,['\n end']); end end end fprintf(fid, '\n\nend\n'); % ******************************************************************* % warning message function fprintf(fid,'\n\n%% -------------------------------------------------------------------'); fprintf(fid,'\n%% function for creating warning messages'); fprintf(fid,['\nfunction ',Comp.name,'warn(idx, msg)']); %fprintf(fid,['\nglobal ',c_name]); fprintf(fid,['\nfm_disp(fm_strjoin(''Warning: ',upper(Comp.name),' #'',int2str(idx),msg))']); % close component file and return fclose(fid); fm_choice(['Function "fm_',Comp.name,'" built.'],2) % **************************************************************** function vect = varvect(vect,sep) n = length(sep)-1; if iscell(vect) vect = fm_strjoin(vect,'#'); vect = strrep([vect{:}],'#',sep); vect(end-n:end) = []; end
github
Sinan81/PSAT-master
symfault.m
.m
PSAT-master/psat-oct/psat/symfault.m
4,578
utf_8
7a0f660fadb898109463adb029ac24ae
% The program symfault is designed for the balanced three-phase % fault analysis of a power system network. The program requires % the bus impedance matrix Zbus. Zbus may be defined by the % user, obtained by the inversion of Ybus or it may be % determined either from the function Zbus = zbuild(zdata) % or the function Zbus = zbuildpi(linedata, gendata, yload). % The program prompts the user to enter the faulted bus number % and the fault impedance Zf. The prefault bus voltages are % defined by the reserved Vector V. The array V may be defined or % it is returned from the power flow programs lfgauss, lfnewton, % decouple or perturb. If V does not exist the prefault bus voltages % are automatically set to 1.0 per unit. The program obtains the % total fault current, the postfault bus voltages and line currents. % % Copyright (C) 1998 H. Saadat function symfault(zdata, Zbus, V) fm_var if ~autorun('Short Circuit Analysis',0) return end if isempty(Fault.con) fm_disp('No fault found', 2) return end zdata = Line.con; [Zbus, zdata]= zbuildpi(zdata, Syn.con); nl = zdata(:,1); nr = zdata(:,2); R = zdata(:,3); X = zdata(:,4); nc = length(zdata(1,:)); if nc > 4 BC = zdata(:,11); elseif nc == 4 BC = zeros(length(zdata(:,1)), 1); end ZB = R + j*X nbr = length(zdata(:,1)); nbus = max(max(nl), max(nr)); if exist('V') == 1 if length(V) == nbus V0 = V; end else V0 = ones(nbus, 1) + j*zeros(nbus, 1); end fprintf('\nThree-phase balanced fault analysis \n') for ff = 1:Fault.n nf = Fault.bus(ff); fprintf('Faulted bus No. = %g \n', nf) fprintf('\n Fault Impedance Zf = R + j*X = ') Zf = Fault.con(ff,7) + j*Fault.con(ff,8); fprintf('%8.5f + j(%8.5f) \n', real(Zf), imag(Zf)) fprintf('Balanced three-phase fault at bus No. %g\n', nf) If = V0(nf)/(Zf + Zbus(nf, nf)); Ifm = abs(If); Ifmang = angle(If)*180/pi; fprintf('Total fault current = %8.4f per unit \n\n', Ifm) fprintf('Bus Voltages during fault in per unit \n\n') fprintf(' Bus Voltage Angle\n') fprintf(' No. Magnitude degrees\n') for n = 1:nbus if n == nf Vf(nf) = V0(nf)*Zf/(Zf + Zbus(nf,nf)); Vfm = abs(Vf(nf)); angv = angle(Vf(nf))*180/pi; else Vf(n) = V0(n) - V0(n)*Zbus(n,nf)/(Zf + Zbus(nf,nf)); Vfm = abs(Vf(n)); angv=angle(Vf(n))*180/pi; end fprintf(' %4g', n), fprintf('%13.4f', Vfm),fprintf('%13.4f\n', angv) end fprintf(' \n') fprintf('Line currents for fault at bus No. %g\n\n', nf) fprintf(' From To Current Angle\n') fprintf(' Bus Bus Magnitude degrees\n') for n = 1:nbus %Ign=0; for I = 1:nbr if nl(I) == n || nr(I) == n if nl(I) == n k = nr(I); elseif nr(I) == n k = nl(I); end if k==0 Ink = (V0(n) - Vf(n))/ZB(I); Inkm = abs(Ink); th = angle(Ink); %if th <= 0 if real(Ink) > 0 fprintf(' G '), fprintf('%7g',n), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) elseif real(Ink) ==0 && imag(Ink) < 0 fprintf(' G '), fprintf('%7g',n), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) end Ign = Ink; elseif k ~= 0 Ink = (Vf(n) - Vf(k))/ZB(I)+BC(I)*Vf(n); %Ink = (Vf(n) - Vf(k))/ZB(I); Inkm = abs(Ink); th=angle(Ink); %Ign=Ign+Ink; %if th <= 0 if real(Ink) > 0 fprintf('%7g', n) fprintf('%10g', k), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) elseif real(Ink) ==0 && imag(Ink) < 0 fprintf('%7g', n) fprintf('%10g', k), fprintf('%12.4f', Inkm) fprintf('%12.4f\n', th*180/pi) end end end end if n == nf % show Fault Current fprintf('%7g',n) fprintf(' F') fprintf('%12.4f', Ifm) fprintf('%12.4f\n', Ifmang) end end resp=0; %while strcmp(resp, 'n')~=1 && strcmp(resp, 'N')~=1 && strcmp(resp, 'y')~=1 && strcmp(resp, 'Y')~=1 %resp = input('Another fault location? Enter ''y'' or ''n'' within single quote -> '); %if strcmp(resp, 'n')~=1 && strcmp(resp, 'N')~=1 && strcmp(resp, 'y')~=1 && strcmp(resp, 'Y')~=1 %fprintf('\n Incorrect reply, try again \n\n'), end %end %if resp == 'y' || resp == 'Y' nf = 999; %else ff = 0; %end end % end for while fm_disp(['Finished "',filedata,'"']),
github
Sinan81/PSAT-master
fm_plot.m
.m
PSAT-master/psat-oct/psat/fm_plot.m
30,010
utf_8
916052824f8021af416d6d8bd704c7d7
function fm_plot(flag) % FM_PLOT plot results of Continuation Power Flow, % Optimal Power Flow and Time Domain % Simulations. % % FM_PLOT(FLAG) % FLAG 0 -> create variable list % 1 -> plot selected variables % 2 -> save graph % 3 -> set layout % %Author: Federico Milano %Date: 11-Nov-2002 %Update: 25-Feb-2003 %Update: 26-Jan-2005 %Version: 1.0.2 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global DAE Bus Syn Settings Fig Snapshot Hdl CPF Theme global Varout Varname Path File OPF Line Mass SSR Pmu %hdls = get(Fig.plot, 'Children') %display(hdls) hdlfig = findobj(Fig.plot, 'Tag','Axes1'); hdlfig2 = findobj(Fig.plot, 'Tag','Axes2'); Hdl_grid = findobj(Fig.plot,'Tag','Checkbox1'); Hdl_legend = findobj(Fig.plot,'Tag','Checkbox2'); Hdl_listvar = findobj(Fig.plot,'Tag','Listbox1'); Hdl_listplot = findobj(Fig.plot,'Tag','Listbox2'); Hdl_tipoplot = findobj(Fig.plot,'Tag','PopupMenu1'); Hdl_angref = findobj(Fig.plot,'Tag','PopupMenu2'); Hdl_snap = findobj(Fig.plot,'Tag','Radiobutton1'); hdl_zoom1 = findobj(Fig.plot,'Tag','Pushbutton12'); hdl_zoom2 = findobj(Fig.plot,'Tag','Pushbutton11'); hdl_zoom3 = findobj(Fig.plot,'Tag','Pushbutton4'); hdl_x = findobj(Fig.plot,'Tag','Pushbutton9'); hdl_y = findobj(Fig.plot,'Tag','Pushbutton5'); hdl_xy = findobj(Fig.plot,'Tag','Pushbutton10'); switch flag case 'exporttext', % output data as plain text file flag = 'plotvars'; out_matlab = 0; out_mtv = 0; out_text = 1; case 'exportmtv', % output data as plain text file flag = 'plotvars'; out_matlab = 0; out_mtv = 1; out_text = 0; case 'exportscript', % output data as plain text file flag = 'plotvars'; out_matlab = 1; out_mtv = 0; out_text = 0; otherwise out_matlab = 0; out_mtv = 0; out_text = 0; end switch flag case 'initlist' if ~strcmp(get(Fig.plot,'UserData'),File.modify) set(Hdl_listvar, ... 'String',enum(Varname.uvars(Varout.idx)), ... 'Value',1); if Settings.hostver < 8.04 set(Fig.plot,'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyle','-'); end end set(Fig.plot,'UserData',File.modify) Varname.pos = 1; case 'initxlabel' first = strrep(Settings.xlabel,'\',''); hdl = findobj(Fig.plot,'Tag','Listbox1'); stringa = get(hdl,'String'); hdl = findobj(Fig.plot,'Tag','PopupMenu3'); if ~isempty(stringa) set(hdl,'String',[{first}; stringa],'Enable','on','Value',1) end case 'plotvars' if isempty(Varout.t) fm_disp('Plotting Utilities: No data available for plotting.') return end if isempty(Varname.pos) fm_disp('Plotting Utilities: Select variables to be plotted.') return end nB = Bus.n; nD = DAE.n; Value = get(Hdl_listvar,'Value'); if isempty(Value), return, end hdlfig = findobj(Fig.plot, 'Tag', 'Axes1'); AxesFont = get(hdlfig,'FontName'); %AxesColor = get(hdlfig,'Color'); %if ~length(AxesColor) AxesColor = [1, 1, 1]; %end AxesWeight = get(hdlfig,'FontWeight'); AxesAngle = get(hdlfig,'FontAngle'); AxesSize = get(hdlfig,'FontSize'); AxesUnits = get(hdlfig,'FontUnits'); plot_snap = get(Hdl_snap,'Value'); snap_idx = zeros(length(Snapshot),1); if plot_snap && ~OPF.init for i = 1:length(Snapshot); a = find(Varout.t == Snapshot(i).time); if isempty(a) fm_disp('Plotting utilities: Snapshots do not match current simulation data',2) Hdl_rad1 = findobj(gcf,'Tag','Radiobutton1'); set(Hdl_rad1,'Value',0); plot_snap = 0; break else snap_idx(i) = a; end end end legenda = Varname.fvars(Varout.idx(Value(Varname.pos))); leg_value = get(Hdl_legend,'Value'); hdlab = findobj(Fig.plot,'Tag','PopupMenu3'); AbValue = get(hdlab,'Value'); Y = Varout.vars(:,Value); if isempty(Y), return, end % set angle unit if Settings.usedegree kdx = get_angle_idx(Value); Y(:,kdx) = 180*Y(:,kdx)/pi; end % set rotor speed unit and values if Settings.usehertz || Settings.userelspeed kdx = get_rotor_idx(Value); if Settings.userelspeed Y(:,kdx) = Y(:,kdx)-1; end if Settings.usehertz Y(:,kdx) = Settings.freq*Y(:,kdx); end end % set reference angle if ~OPF.init ang_idx = get(Hdl_angref,'Value')-1; if ~ang_idx angolo = zeros(length(Varout.t),1); else ref_idx = get(Hdl_angref,'UserData'); ang_ref = ref_idx(ang_idx); angolo = Varout.vars(:,ang_ref); end for i = 1:length(Value) kk = Varout.idx(Value(i)); if isdelta_syn(Syn,kk) || isdelta_mass(Mass,kk) || isdelta_ssr(SSR,kk) || isdelta_pmu(Pmu,kk) Y(:,i) = Y(:,i) - angolo; elseif kk >= nD+1 && kk <= nD+nB Y(:,i) = Y(:,i) - angolo; end end end hdlnorm = findobj(Fig.plot,'Tag','NormSij'); if strcmp(get(hdlnorm,'Checked'),'on') for i = 1:length(Value) kk = Varout.idx(Value(i)); Y(:,i) = isflow_line(Line,Y(:,i),kk); end end if AbValue == 1 X = Varout.t; else X = Varout.vars(:,AbValue-1); % set angle unit check = get_angle_idx(AbValue-1); if Settings.usedegree && ~isempty(check) X = 180*X/pi; end % set rotor speed unit and values if Settings.usehertz || Settings.userelspeed check = get_rotor_idx(AbValue-1); if Settings.userelspeed && check X = X-1; end if Settings.usehertz && check X = Settings.freq*X; end end end tipoplot = get(Hdl_tipoplot,'Value'); if out_text plainfile = fm_filenum('txt'); fid = fopen([Path.data,plainfile,'.txt'],'wt'); if fid == -1 fm_disp('Cannot open file. Data not saved.') return end fprintf(fid,'C Legend:\n'); fprintf(fid,'C %s, ',Settings.xlabel); for i = 1:size(Y,2) fprintf(fid,'%s, ',legenda{i}); end fprintf(fid,'\nC Data:\n'); fprintf(fid,[repmat('%8.5f ',1,1+size(Y,2)),'\n'],[X,Y]'); fclose(fid); fm_disp(['Data exported to plain text file "',plainfile,'.txt"']) end if out_mtv plainfile = fm_filenum('mtv'); fid = fopen([Path.data,plainfile,'.mtv'],'wt'); if fid == -1 fm_disp('Cannot open file. Data not saved.') return end %fprintf(fid,'$ DATA=CURVE2D\n'); fprintf(fid,'%% xlabel = "%s"\n',Settings.xlabel); if min(X) < max(X) fprintf(fid,'%% xmin = %8.5f\n',min(X)); fprintf(fid,'%% xmax = %8.5f\n',max(X)); end fprintf(fid,'\n'); if tipoplot == 3 || tipoplot == 6 fm_disp('MTV format does not support numbered plots.') end for i = 1:size(Y,2) labelmtv = strrep(legenda{i},'{',''); labelmtv = strrep(labelmtv,'}',''); labelmtv = strrep(labelmtv,'_',' '); labelmtv = strrep(labelmtv,'\',''); fprintf(fid,'%% linelabel="%s"\n',labelmtv); switch tipoplot case 2 linetype = rem(i-1,10)+1; linecolor = 1; markertype = 0; markercolor = 1; case 4 linetype = 1; linecolor = 1; markertype = rem(i-1,13)+1; markercolor = 1; case 5 linetype = 1; linecolor = rem(i-1,10)+1; markertype = rem(i-1,13)+1; markercolor = linecolor; otherwise linetype = 1; linecolor = rem(i-1,10)+1; markertype = 0; markercolor = 1; end fprintf(fid,'%% linetype=%d linecolor=%d markertype=%d markercolor=%d\n', ... linetype,linecolor,markertype,markercolor); fprintf(fid,'%8.5f %8.5f\n',[X,Y(:,i)]'); fprintf(fid,'\n'); end fclose(fid); fm_disp(['Data exported to MTV plot file "',plainfile,'.mtv"']) end if out_matlab plainfile = fm_filenum('m'); fid = fopen([Path.data,plainfile,'.m'],'wt'); if fid == -1 fm_disp('Cannot open file. Data not saved.') return end fprintf(fid,'x_label = ''%s'';\n',Settings.xlabel); fprintf(fid,'\nvar_legend = {'); for i = 1:size(Y,2)-1 fprintf(fid,'''%s'', ',legenda{i}); end fprintf(fid,'''%s''};\n',legenda{end}); fprintf(fid,'\noutput_data = [ ...\n'); fprintf(fid,[repmat('%8.5f ',1,1+size(Y,2)),';\n'], ... [X(1:end-1),Y(1:end-1,:)]'); fprintf(fid,[repmat('%8.5f ',1,1+size(Y,2)),'];\n'], ... [X(end),Y(end,:)]'); fclose(fid); fm_disp(['Data exported to plain text file "',plainfile,'.m"']) end set(Fig.plot,'CurrentAxes',hdlfig); plot(X,Y(:,Varname.pos)); set(hdlfig, 'Tag', 'Axes1') if AbValue == 1 xlabel(Settings.xlabel); else xlabel(Varname.fvars{Varout.idx(AbValue-1)}); end if min(X) < max(X) set(hdlfig,'XLim',[min(X),max(X)]) end %legend if leg_value == 1 || Settings.hostver >= 7 if Settings.hostver >= 8.04 hleg = legend(legenda, 'Location', 'northeast'); else hleg = legend(legenda, 0); end Hdl.legend = hleg; set(hleg,'Color',AxesColor) hchild = get(hleg,'Child'); if ishandle(hchild) set(hchild(end), ... 'FontName',AxesFont, ... 'FontWeight',AxesWeight, ... 'FontAngle',AxesAngle) end end hdlfig = findobj(Fig.plot, 'Tag', 'Axes1'); % display(hdlfig) % axes(hdlfig) if tipoplot == 3 || tipoplot == 6 [quanti,tanti] = size(Y); colori = get(gcf,'DefaultAxesColorOrder'); for i = 1:tanti if plot_snap sequenza = snap_idx; else tmin = min(X); tmax = max(X); deltat = (tmax-tmin)/5; tmin = tmin + i*(tmax-tmin)/43; seqt = tmin:deltat:tmax; for j = 1:length(seqt), [valt, sequenza(j)] = min(abs(X-seqt(j))); end end hdl = text(X(sequenza),Y(sequenza,i),num2str(Varname.pos(i))); if tipoplot == 6, set(hdl,'Color',colori(rem(i-1,7)+1,:)); end end if leg_value == 1 || Settings.hostver >= 7 hdl = findobj(Fig.plot,'Tag','legend'); %get(hdl) oldh = gca; set(gca,'HandleVisibility','off') set(hdl,'Interruptible','on') h = findobj(hdl,'Type','line'); %get(hdl) for i = 1:tanti j = i*2; xdata = get(h(j),'XData'); ydata = get(h(j),'YData'); htext = text((xdata(2)-xdata(1))/2,ydata(1), ... int2str(tanti-i+1)); set(htext,'Color',get(h(j),'Color')); end set(oldh,'HandleVisibility','on') set(Fig.plot,'CurrentAxes',oldh); end elseif tipoplot == 4 || tipoplot == 5 [quanti,tanti] = size(Y); hold on simboli = {'o';'s';'d';'v';'^';'<';'>';'x'}; colori = get(Fig.plot,'DefaultAxesColorOrder'); for i = 1:tanti if plot_snap sequenza = snap_idx; if tanti == 1 && CPF.init y1 = get(hdlfig,'YLim'); yoff = 0.05*(y1(2)-y1(1)); for hh = 1:length(sequenza) text(X(sequenza(hh)), ... Y(sequenza(hh),Varname.pos(i))+yoff, ... Snapshot(hh).name) end end else tmin = min(X); tmax = max(X); deltat = (tmax-tmin)/5; tmin = tmin + i*(tmax-tmin)/43; seqt = tmin:deltat:tmax; for j = 1:length(seqt), [valt, sequenza(j)] = min(abs(X-seqt(j))); end end set(hdlfig,'LineStyle',simboli{rem(i-1,8)+1}, 'Tag', 'Axes1'); hmarker = plot(X(sequenza),Y(sequenza,Varname.pos(i))); set(hmarker,'MarkerSize',7,'MarkerFaceColor',AxesColor); if tipoplot == 5, set(hmarker,'Color',colori(rem(i-1,7)+1,:)); end end hold off; if leg_value == 1 || Settings.hostver >= 7 hdl = findobj(Fig.plot,'Tag','legend'); set(Fig.plot,'CurrentAxes',hdl); h = findobj(hdl,'Type','line'); for i = 1:tanti j = i*2; xdata = get(h(j),'XData'); ydata = get(h(j),'YData'); set(hdl,'LineStyle',simboli{rem(tanti-i,8)+1}); if Settings.hostver >= 7 hmarker = plot(hdl,(xdata(2)-xdata(1))/1.2,ydata(1)); else hmarker = plot((xdata(2)-xdata(1))/1.2,ydata(1)); end set(hmarker,'MarkerSize',7, ... 'Color',get(h(j),'Color'), ... 'MarkerFaceColor',AxesColor); end set(Fig.plot,'CurrentAxes',hdlfig); end end if get(Hdl_grid,'Value'); grid on; end if ~get(Hdl_legend,'Value') && Settings.hostver >= 7 && Settings.hostver < 8.04 legend(findobj(Fig.plot,'Tag','Axes1'),'hide') end set(get(hdlfig,'XLabel'), ... 'FontName',AxesFont, ... 'FontWeight',AxesWeight, ... 'FontAngle',AxesAngle, ... 'FontSize',AxesSize, ... 'FontUnits',AxesUnits) set(hdlfig, ... 'FontName',AxesFont, ... 'Color',AxesColor, ... 'FontWeight',AxesWeight, ... 'FontAngle',AxesAngle, ... 'FontSize',AxesSize, ... 'FontUnits',AxesUnits, ... 'Tag','Axes1') if ishandle(Fig.line), fm_plot('createlinelist'), end if get(hdl_x, 'Value'), fm_plot('axesx'), end if get(hdl_y, 'Value'), fm_plot('axesy'), end if get(hdl_xy,'Value'), fm_plot('axesxy'), end fm_plot plotvlims fm_plot plotslims set(hdlfig,'Position',[0.09 0.4050 0.4754 0.5000], 'Tag', 'Axes1') %display('ciao') %display(hdlfig) case 'export' % export the figure to file tag = get(gcbo,'Tag'); axs_pos = get(Hdl.axesplot,'Position'); fig_pos = get(Fig.plot,'Position'); pap_pos = get(Fig.plot,'PaperPosition'); pap_siz = get(Fig.plot,'PaperSize'); leg_value = get(Hdl_legend,'Value'); if leg_value pos_leg = get(Hdl.legend,'Position'); end shrink = 0.8; % axes scale factor set(Hdl.axesplot,'Position',[0.13 0.11 0.855 0.875]) set(Fig.plot,'Position',[fig_pos(1), fig_pos(2), ... fig_pos(3)*shrink, fig_pos(4)*shrink]) if leg_value pos_leg2(1) = 0.13 + 0.855*(pos_leg(1) - axs_pos(1))/axs_pos(3); pos_leg2(2) = 0.11 + 0.875*(pos_leg(2) - axs_pos(2))/axs_pos(4); pos_leg2(3) = pos_leg(3)*0.855/axs_pos(3); pos_leg2(4) = pos_leg(4)*0.875/axs_pos(4); set(Hdl.legend,'Position',pos_leg2); if pos_leg2(1)+pos_leg2(3) > 0.985 Resize = (pos_leg2(1)+pos_leg2(3))/0.985; fig_pos2 = [0.13 0.11 0.855 0.875]; fig_pos2(3) = fig_pos2(3)/Resize; fig_pos2(1) = fig_pos2(1)/Resize; pos_leg2(3) = pos_leg2(3)/Resize; pos_leg2(1) = pos_leg2(1)/Resize; set(Hdl.axesplot,'Position',fig_pos2) set(Hdl.legend,'Position',pos_leg2) end end if Settings.hostver > 5.03, set(Fig.plot,'PaperSize',[pap_siz(1)*shrink, pap_siz(2)*shrink]) end ppos(3) = pap_pos(3)*shrink; ppos(4) = pap_pos(4)*shrink; ppos(1) = (pap_siz(1)-ppos(3))/2; ppos(2) = (pap_siz(2)-ppos(4))/2; set(Fig.plot,'PaperPosition',ppos) ax2_pos = get(Hdl.axeslogo,'Position'); set(Hdl.axeslogo,'Position',[10 10 0.2 0.2]); Hdl_all = get(Fig.plot,'Children'); idx = find(Hdl_all==Hdl.axesplot); if idx, Hdl_all(idx) = []; end idx = find(Hdl_all==Hdl.axeslogo); if idx, Hdl_all(idx) = []; end if leg_value, idx = find(Hdl_all==Hdl.legend); if idx, Hdl_all(idx) = []; end end set(Hdl_all,'Visible','off'); lastwarn('') switch tag case 'PushEPS' nomefile = fm_filenum('eps'); print(Fig.plot,'-depsc',[Path.data,nomefile]) set(hdlfig,'Position',axs_pos); set(hdlfig2,'Position',ax2_pos); set(Fig.plot,'Position',fig_pos) set(Fig.plot,'PaperPosition',pap_pos) if Settings.hostver > 5.03, set(Fig.plot,'PaperSize',pap_siz) end set(Hdl_all,'Visible','on'); if leg_value set(Hdl.legend,'Position',pos_leg); end case 'PushMeta' print(Fig.plot,'-dmeta') set(hdlfig,'Position',axs_pos); set(hdlfig2,'Position',ax2_pos); set(Fig.plot,'Position',fig_pos) set(Fig.plot,'PaperPosition',pap_pos) if Settings.hostver > 5.03, set(Fig.plot,'PaperSize',pap_siz) end set(Hdl_all,'Visible','on'); if leg_value set(Hdl.legend,'Position',pos_leg); end case 'PushFig' figplot = Fig.plot; Fig.plot = -1; try figpos = get(0,'factoryFigurePosition'); axspos = get(0,'factoryAxesPosition'); figunit = get(0,'factoryFigureUnits'); axsunit = get(0,'factoryAxesUnits'); catch figpos = [100 100 660 520]; axspos = [0.1300 0.1100 0.7750 0.8150]; figunit = 'pixels'; axsunit = 'normalized'; end set(figplot, ... 'Units',figunit, ... 'Position',figpos, ... 'Menubar','figure', ... 'Name','', ... 'NumberTitle','on', ... 'CreateFcn','', ... 'DeleteFcn','', ... 'UserData',[], ... 'FileName','') set(Hdl.axesplot,'Color',[1 1 1],'Units',axsunit,'Position',axspos) if leg_value set(Hdl.legend,'Color',[1 1 1]) end delete(Hdl_all) delete(hdlfig2) fm_plotfig figure(figplot) end if ~isempty(lastwarn) && ~strcmp(lastwarn,'File not found or permission denied') fm_disp(lastwarn,2), end case 'plottypes' tipoplot = get(Hdl_tipoplot,'Value'); if Settings.hostver < 8.04 switch tipoplot case 1, set(Fig.plot, ... 'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyleOrder','-'); case 2, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-|-.|--|:'); case 3, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-'); case 4, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-'); otherwise, set(Fig.plot, ... 'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyleOrder','-'); end else switch tipoplot case 1, set(Fig.plot, ... 'DefaultAxesColorOrder',Settings.color, ... 'DefaultAxesLineStyleOrder','-'); otherwise, set(Fig.plot, ... 'DefaultAxesColorOrder',[ 0 0 0 ], ... 'DefaultAxesLineStyleOrder','-|-.|--|:'); end end fm_plot('plotvars') case 'editvarname' value = get(Hdl_listplot,'Value'); if ~isempty(get(Hdl_listplot,'String')) valori = get(Hdl_listvar,'Value'); val = valori(Varname.pos(value)); stringa = Varname.fvars(Varname.idx); nomeattuale = popupstr(Hdl_listplot); idx = findstr(nomeattuale,']'); nomeattuale = nomeattuale(idx+2:end); nomenuovo = fm_input('Input Formatted Text:', ... 'Legend Name',1,{stringa{val}}); if isempty(nomenuovo), return, end Varname.fvars{Varname.idx(val)} = nomenuovo{1}; set(Fig.plot,'UserData',stringa); fm_disp(['Formatted text of variable "', ... nomeattuale,'" has been changed in "', ... nomenuovo{1},'"']) else fm_disp('No variable selected') end case 'zoomy' zoom yon set(Fig.plot,'WindowButtonMotionFcn','fm_plot motion'); set(hdl_zoom1,'Value',0); set(hdl_zoom2,'Value',0); if get(hdl_zoom3,'Value') Settings.zoom = 'zoom yon'; else Settings.zoom = ''; zoom off end case 'axesy' if get(hdl_x,'Value') set(hdl_x,'Value',0) delete(findobj(allchild(hdlfig),'UserData','x axis')) end if get(hdl_xy,'Value') set(hdl_xy,'Value',0) delete(findobj(allchild(hdlfig),'UserData','x axis')) delete(findobj(allchild(hdlfig),'UserData','y axis')) end value = get(gcbo,'Value'); if value ylim = get(hdlfig,'YLim'); hold on h = plot([0 0],[ylim(1), ylim(2)],'k:'); set(h,'UserData','y axis') hold off else hdl_child = allchild(hdlfig); delete(findobj(hdl_child,'UserData','y axis')) end if ishandle(Fig.line), fm_plot('createlinelist'), end case 'axescolor' currentColor = get(hdlfig,'Color'); c = uisetcolor(currentColor); if ~isequal(c,currentColor) set(hdlfig,'Color',c) hdl_line = findobj(allchild(hdlfig),'Type','line'); set(hdl_line,'MarkerFaceColor',c) hlegend = findobj(Fig.plot,'Tag','legend'); set(hlegend,'Color',c) end case 'axesx' if get(hdl_y,'Value') set(hdl_y,'Value',0) delete(findobj(allchild(hdlfig),'UserData','y axis')) end if get(hdl_xy,'Value') set(hdl_xy,'Value',0) delete(findobj(allchild(hdlfig),'UserData','y axis')) delete(findobj(allchild(hdlfig),'UserData','x axis')) end value = get(gcbo,'Value'); if value xlim = get(hdlfig,'XLim'); hold on h = plot([xlim(1), xlim(2)], [0, 0],'k:'); set(h,'UserData','x axis') hold off else hdl_child = allchild(hdlfig); delete(findobj(hdl_child,'UserData','x axis')) end if ishandle(Fig.line), fm_plot('createlinelist'), end case 'axesxy' if get(hdl_x,'Value') set(hdl_x,'Value',0) delete(findobj(allchild(hdlfig),'UserData','x axis')) end if get(hdl_y,'Value') set(hdl_y,'Value',0) delete(findobj(allchild(hdlfig),'UserData','y axis')) end value = get(gcbo,'Value'); if value xlim = get(hdlfig,'XLim'); ylim = get(hdlfig,'YLim'); hold on h = plot([xlim(1), xlim(2)], [0, 0],'k:'); set(h,'UserData','x axis') h = plot([0, 0],[ylim(1), ylim(2)],'k:'); set(h,'UserData','y axis') hold off else hdl_child = allchild(hdlfig); try delete(findobj(hdl_child,'UserData','x axis')) catch % nothing to do end try delete(findobj(hdl_child,'UserData','y axis')) catch % nothing to do end end if ishandle(Fig.line), fm_plot('createlinelist'), end case 'zoomx' zoom xon set(Fig.plot,'WindowButtonMotionFcn','fm_plot motion'); set(hdl_zoom1,'Value',0); set(hdl_zoom3,'Value',0); if get(hdl_zoom2,'Value') Settings.zoom = 'zoom xon'; else Settings.zoom = ''; zoom off end case 'zoomxy' zoom on set(Fig.plot,'WindowButtonMotionFcn','fm_plot motion'); set(hdl_zoom2,'Value',0); set(hdl_zoom3,'Value',0); if get(hdl_zoom1,'Value') Settings.zoom = 'zoom on'; else Settings.zoom = ''; zoom off end case 'moveup' value = get(Hdl_listplot,'Value'); NameString = get(Hdl_listplot,'String'); Value = 1:length(NameString); if value > 1 dummy = Varname.pos(value); Varname.pos(value) = Varname.pos(value-1); Varname.pos(value-1) = dummy; dummy = Value(value); Value(value) = Value(value-1); Value(value-1) = dummy; set(Hdl_listplot, ... 'String',NameString(Value), ... 'Value',value-1); end case 'movedown' value = get(Hdl_listplot,'Value'); NameString = get(Hdl_listplot,'String'); Value = 1:length(NameString); if value < length(Varname.pos) && ~isempty(NameString) dummy = Varname.pos(value); Varname.pos(value) = Varname.pos(value+1); Varname.pos(value+1) = dummy; dummy = Value(value); Value(value) = Value(value+1); Value(value+1) = dummy; set(Hdl_listplot, ... 'String',NameString(Value), ... 'Value',value+1); end case 'togglegrid' if get(gcbo,'Value') grid on else grid off end case 'togglelegend' if Settings.hostver >= 8.04 % axes(findobj(Fig.plot, 'Tag', 'Axes1')) legend toggle elseif Settings.hostver >= 7 legend(findobj(Fig.plot,'Tag','Axes1'),'toggle') else onoff = {'off','on'}; if strcmp(get(gcbo,'Tag'),'PushLegend') set(Hdl_legend,'Value',~get(Hdl_legend,'Value')) set(gcbo,'Checked',onoff{get(Hdl_legend,'Value')+1}) value = get(Hdl_legend,'Value'); else hdl = findobj(Fig.plot,'Tag','PushLegend'); set(hdl,'Checked',onoff{get(gcbo,'Value')+1}) value = get(gcbo,'Value'); end if value fm_plot('plotvars') else legend off end end case 'listvars' Value = get(Hdl_listvar,'Value'); if isempty(Value), return, end NameString = get(Hdl_listvar,'String'); if isempty(NameString), return, end set(Hdl_listplot,'String',NameString(Value)); set(Hdl_listplot,'Value',1); Varname.pos = 1:length(Value); if strcmp(get(Fig.plot,'SelectionType'),'open'), fm_plot('plotvars') end case 'listlines' hdl = findobj(Fig.line,'Tag','Listbox1'); Value = get(hdl,'Value'); hdl_line = get(Fig.line,'UserData'); hdl_line = hdl_line(end:-1:1); fm_linedlg(hdl_line(Value)) case 'createlinelist' hdl_line = findobj(allchild(hdlfig),'Type','line'); variabili = get(Hdl_listplot,'String'); set(Fig.line,'UserData',hdl_line); hdl_list = findobj(Fig.line,'Tag','Listbox1'); line_string = cell(length(hdl_line),1); hdl_line = hdl_line(end:-1:1); for i = 1:length(hdl_line) if strcmp(get(hdl_line(i),'UserData'),'x axis') line_string{i,1} = ['x axis ',fvar(i,4)]; elseif strcmp(get(hdl_line(i),'UserData'),'y axis') line_string{i,1} = ['y axis ',fvar(i,4)]; elseif i <= length(variabili) line_string{i,1} = ['line ',fvar(i,4),variabili{i}]; else line_string{i,1} = ['symbol ',fvar(i,4), ... variabili{i-length(variabili)}]; end end set(hdl_list,'String',line_string,'Value',1); case 'axesprops' fm_axesdlg(hdlfig) case 'textprops' TextProp = uisetfont; if isstruct(TextProp) set(hdlfig,TextProp) set(get(hdlfig,'XLabel'),TextProp) set(get(hdlfig,'YLabel'),TextProp) set(get(hdlfig,'Title'),TextProp) if get(Hdl_legend,'Value') hlegend = findobj(Fig.plot,'Tag','legend'); hchild = get(hlegend,'Child'); set(hchild(end), ... 'FontName',TextProp.FontName, ... 'FontWeight', TextProp.FontWeight, ... 'FontAngle',TextProp.FontAngle) end end case 'setxlabel' value = get(gcbo,'Value'); set(gcbo,'Value',value(end)) if strcmp(get(Fig.plot,'SelectionType'),'open') fm_plot('plotvars') end case 'setangles' [idx,kdx] = get_angle_idx; set(gcbo,'String',[{'None'}; Varname.uvars(idx)],'UserData',kdx) case 'limits' status = get(gcbo,'Checked'); switch status case 'on' set(gcbo,'Checked','off') case 'off' set(gcbo,'Checked','on') end fm_plot plotvars case 'usedegrees' status = get(gcbo,'Checked'); switch status case 'on' Settings.usedegree = 0; set(gcbo,'Checked','off') case 'off' Settings.usedegree = 1; set(gcbo,'Checked','on') end fm_plot plotvars case 'usehertzs' status = get(gcbo,'Checked'); switch status case 'on' Settings.usehertz = 0; set(gcbo,'Checked','off') case 'off' Settings.usehertz = 1; set(gcbo,'Checked','on') end fm_plot plotvars case 'userelspeeds' status = get(gcbo,'Checked'); switch status case 'on' Settings.userelspeed = 0; set(gcbo,'Checked','off') case 'off' Settings.userelspeed = 1; set(gcbo,'Checked','on') end fm_plot plotvars case 'plotvlims' hdl = findobj(Fig.plot,'Tag','PlotVLim'); value = get(hdl,'Checked'); if ~strcmp(value,'on'), return, end xlimits = get(hdlfig,'XLim'); hold on plot(hdlfig,[xlimits(1) xlimits(2)],[0.9 0.9],'k:') plot(hdlfig,[xlimits(1) xlimits(2)],[1.1 1.1],'k:') hold off case 'plotslims' hdl = findobj(Fig.plot,'Tag','NormSij'); value = get(hdl,'Checked'); if ~strcmp(value,'on'), return, end xlimits = get(hdlfig,'XLim'); hold on plot(hdlfig,[xlimits(1) xlimits(2)],[1.0 1.0],'k:') hold off case 'lowestv' idx = find(Varname.idx > DAE.n+Bus.n && Varname.idx <= DAE.n+2*Bus.n); if isempty(idx), return, end out = Varout.vars(:,idx); vals = min(out,[],1); [y,jdx] = sort(vals); if length(jdx) > 3, jdx = jdx(1:3); end set(Hdl_listvar,'Value',idx(jdx)); fm_plot listvars fm_plot plotvars case 'highestv' idx = find(Varname.idx > DAE.n+Bus.n && Varname.idx <= DAE.n+2*Bus.n); if isempty(idx), return, end out = Varout.vars(:,idx); vals = max(out,[],1); [y,jdx] = sort(vals,2,'descend'); if length(jdx) > 3, jdx = jdx(1:3); end set(Hdl_listvar,'Value',idx(jdx)); fm_plot listvars fm_plot plotvars case 'highests' values = highests_line(Line); if isempty(values), return, end set(Hdl_listvar,'Value',values); fm_plot listvars fm_plot plotvars end if ~isempty(Settings.zoom), eval(Settings.zoom), end % ------------------------------------------------------------------------ % Some useful functions % ----------------------------------------------------------------------- function stringa = enum(stringa) for i = 1:length(stringa), stringa{i} = ['[',int2str(i),'] ',stringa{i}]; end function kdx = get_rotor_idx(idx) global DAE Syn COI Cswt Dfig Ddsg Busfreq Mass SSR Tg kdx = []; for i = 1:length(idx) kkk = idx(i); if kkk > DAE.n+DAE.m break elseif kkk <= DAE.n if isomega_syn(Syn,kkk) || isomega_cswt(Cswt,kkk) || isomega_dfig(Dfig,kkk) ... || isomega_ddsg(Ddsg,kkk) || isomega_mass(Mass,kkk) || isomega_ssr(SSR,kkk) ... || isomega_busfreq(Busfreq) kdx = [kdx, i]; end elseif isomega_coi(COI,kkk) || isomega_tg(Tg,kkk) kdx = [kdx, i]; end end function varargout = get_angle_idx(varargin) global Varout DAE Syn Bus COI Mass SSR Phs Svc Cswt Ddsg Dfig Pmu Hvdc idx = []; kdx = []; if ~nargin varidx = Varout.idx; else varidx = varargin{1}; end for i = 1:length(varidx) kkk = varidx(i); if kkk > DAE.n+DAE.m break elseif kkk <= DAE.n if isdelta_syn(Syn,kkk) || isdelta_mass(Mass,kkk) || isdelta_ssr(SSR,kkk) ... || isdelta_phs(Phs,kkk) || isdelta_svc(Svc,kkk) || isdelta_cswt(Cswt,kkk) ... || isdelta_ddsg(Ddsg,kkk) || isdelta_dfig(Dfig,kkk) || isdelta_pmu(Pmu,kkk) idx = [idx, kkk]; kdx = [kdx, i]; end elseif kkk > DAE.n && kkk <= DAE.n+Bus.n idx = [idx, kkk]; kdx = [kdx, i]; elseif isdelta_coi(COI,kkk) || isdelta_hvdc(Hvdc,kkk) idx = [idx, kkk]; kdx = [kdx, i]; end end switch nargout case 1 varargout{1} = kdx; case 2 varargout{1} = idx; varargout{2} = kdx; end
github
Sinan81/PSAT-master
fm_uwfig.m
.m
PSAT-master/psat-oct/psat/fm_uwfig.m
36,174
utf_8
e21245f8662dfac8f223c8e9980016a2
function fig = fm_uwfig(varargin) % FM_UWFIG create GUI for PSAT/UWPFLOW interface. % % FIG = FM_UWFIG % %see UWPFLOW structure for settings % %Author: Federico Milano %Date: 31-Mar-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2019 Federico Milano global Settings Path PQ UWPFLOW GAMS Theme Fig Hdl History % initialize UWPFLOW.opt, if necessary fm_uwpflow('init') % check for options if nargin, checkon(varargin{1}), return, end % do not redraw figure if open if ishandle(Fig.uwpflow), figure(Fig.uwpflow), return, end [u,w] = system('uwpflow'); if isempty(strmatch('UW Continuation Power Flow',w)) uiwait(fm_choice('UWPFLOW is not properly installed on your system.',2)) return end % constants and lists D = 0.9394; dy = 0.025; dx = (D-4*dy)/3; x1 = 0.0329 + dy; x2 = 0.0329 + 2*dy + dx; x3 = 0.0329 + 3*dy + 2*dx; methods = {'[ ] Power Flow'; '[-c] Continuation Method'; '[-C] Direct Method'; '[-H] Parameterized CM'}; output = {'.k'; '.v'; '.w'; '.pf'; '.jac'; '.cf'; '.cpf'; '.mis'; '.var'; '.log'; '.oh'; '.vp'; '.gen'; '.ini'; '.poc'; '.ntv'}; output = fm_strjoin(UWPFLOW.file,output); if PQ.n PQbuses = fm_strjoin('PQ_',num2str(PQ.bus)); if PQ.n < UWPFLOW.opt.B.num, UWPFLOW.opt.B.num = 1; end if PQ.n < UWPFLOW.opt.f.num, UWPFLOW.opt.f.num = 1; end if PQ.n < UWPFLOW.opt.one.num, UWPFLOW.opt.one.num = 1; end else PQbuses = {'<none>'}; end if strcmp(Settings.platform,'MAC') aligntxt = 'center'; dm = 0.0075; else aligntxt = 'left'; dm = 0; end h0 = figure('Units','normalized', ... 'Color',Theme.color02, ... 'Colormap',[], ... 'CreateFcn', 'Fig.uwpflow = gcf;', ... 'DeleteFcn', 'Fig.uwpflow = -1;', ... 'MenuBar','none', ... 'Name','PSAT-UWPFLOW', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',sizefig(1.2*0.5645,1.1*0.8451), ... 'Resize','on', ... 'ToolBar','none', ... 'FileName','fm_uwfig'); fm_set colormap % Menu File h1 = uimenu('Parent',h0, ... 'Label','File', ... 'Tag','MenuFile'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow view', ... 'Label','View UWPFLOW Input/Output files', ... 'Tag','OTV', ... 'Accelerator','g'); h2 = uimenu('Parent',h1, ... 'Callback','close(gcf)', ... 'Label','Exit', ... 'Tag','NetSett', ... 'Accelerator','x', ... 'Separator','on'); % Menu Edit h1 = uimenu('Parent',h0, ... 'Label','Edit', ... 'Tag','MenuEdit'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow makecom', ... 'Label','Create UWPFLOW command line', ... 'Tag','ToolUWcom', ... 'Accelerator','c'); h2 = uimenu('Parent',h1, ... 'Callback','fm_setting', ... 'Label','General Settings', ... 'Tag','ToolSett', ... 'Separator', 'on', ... 'Accelerator','s'); % Menu Run h1 = uimenu('Parent',h0, ... 'Label','Run', ... 'Tag','MenuRun'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow uwrun', ... 'Label','Run UWPFLOW', ... 'Tag','ToolOPFSett', ... 'Accelerator','z'); % Menu Options h1 = uimenu('Parent',h0, ... 'Label','Options', ... 'Tag','MenuOpt'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig a', ... 'Label','[-a] No tap/angle limit control', ... 'Tag','aopt', ... 'Checked',onoff(UWPFLOW.opt.a.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig A', ... 'Label','[-A] No intercahnge area control', ... 'Tag','Aopt', ... 'Checked',onoff(UWPFLOW.opt.A.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig b', ... 'Label','[-b] No interchange area control', ... 'Tag','bopt', ... 'Checked',onoff(UWPFLOW.opt.b.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig d', ... 'Label','[-d] Generate debug output', ... 'Tag','dopt', ... 'Checked',onoff(UWPFLOW.opt.d.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig g', ... 'Label','[-g] Force Qg to 0 (IEEE CDF)', ... 'Tag','gopt', ... 'Checked',onoff(UWPFLOW.opt.g.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig G', ... 'Label','[-G] Turn off ac device recovery', ... 'Tag','Gopt', ... 'Checked',onoff(UWPFLOW.opt.G.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig n', ... 'Label','[-n] Turn off all ac limits', ... 'Tag','nopt', ... 'Checked',onoff(UWPFLOW.opt.n.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig N', ... 'Label','[-N] Turn off all ac system controls', ... 'Tag','Nopt', ... 'Checked',onoff(UWPFLOW.opt.N.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig p', ... 'Label','[-p] Turn off P/Q limits in reg. transf.', ... 'Tag','popt', ... 'Checked',onoff(UWPFLOW.opt.p.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig P', ... 'Label','[-P] Turn off P/Q control by reg. transf.', ... 'Tag','Popt', ... 'Checked',onoff(UWPFLOW.opt.P.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig q', ... 'Label','[-q] Turn off Q limits in PV buses', ... 'Tag','qopt', ... 'Checked',onoff(UWPFLOW.opt.q.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig qx', ... 'Label','[-qx] Turn off V limits in BX buses', ... 'Tag','qxopt', ... 'Checked',onoff(UWPFLOW.opt.qx.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig qz', ... 'Label','[-qz] Turn off Q limits in BZ buses', ... 'Tag','qzopt', ... 'Checked',onoff(UWPFLOW.opt.qz.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig Q', ... 'Label','[-Q] Turn off remote Vg control', ... 'Tag','Qopt', ... 'Checked',onoff(UWPFLOW.opt.Q.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig QX', ... 'Label','[-QX] Turn off remote Vg control in BX buses', ... 'Tag','QXopt', ... 'Checked',onoff(UWPFLOW.opt.QX.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig r', ... 'Label','[-r] Turn off V limits in reg. tranf. and PV buses', ... 'Tag','ropt', ... 'Checked',onoff(UWPFLOW.opt.r.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig R', ... 'Label','[-R] Turn off V control by reg. transf.', ... 'Tag','Ropt', ... 'Checked',onoff(UWPFLOW.opt.R.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig s', ... 'Label','[-s] Suppress ASCII output file', ... 'Tag','sopt', ... 'Checked',onoff(UWPFLOW.opt.s.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig x', ... 'Label','[-x] Use single slack bus', ... 'Tag','xopt', ... 'Checked',onoff(UWPFLOW.opt.x.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig X', ... 'Label','[-X] Turn off max Pg limits', ... 'Tag','Xopt', ... 'Checked',onoff(UWPFLOW.opt.X.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig four', ... 'Label','[-4] Turn off Eq limits in all gen.', ... 'Tag','fouropt', ... 'Checked',onoff(UWPFLOW.opt.four.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig five', ... 'Label','[-5] Turn off Ia limits in all gen.', ... 'Tag','fiveopt', ... 'Checked',onoff(UWPFLOW.opt.five.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig seven', ... 'Label','[-7] Enforce Vmax and Vmin', ... 'Tag','sevenopt', ... 'Checked',onoff(UWPFLOW.opt.seven.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig eight', ... 'Label','[-8] Enforce Imax limits', ... 'Tag','eightopt', ... 'Checked',onoff(UWPFLOW.opt.eight.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig nine', ... 'Label','[-9] Do not enforce gen. Smax limits', ... 'Tag','nineopt', ... 'Checked',onoff(UWPFLOW.opt.nine.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig bound', ... 'Label','[-#] Use secondary voltage control', ... 'Tag','boundopt', ... 'Checked',onoff(UWPFLOW.opt.bound.status)); % Menu Output files h1 = uimenu('Parent',h0, ... 'Label','Output', ... 'Tag','MenuOut'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig E', ... 'Label','[-E] Print PoC right e-vector', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.E.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig j', ... 'Label','[-j] Write Jacobian matrix (2n+1)x(2n+1)', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.j.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig J', ... 'Label','[-J] Write Jacobian matrix (2n)x(2n)', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.j.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig E', ... 'Label','[-E] Print PoC right e-vector', ... 'Tag','eopt', ... 'Checked',onoff(UWPFLOW.opt.E.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig l', ... 'Label','[-l] Write standard error output', ... 'Tag','lopt', ... 'Checked',onoff(UWPFLOW.opt.l.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig w', ... 'Label','[-w] Write solution in IEEE CARD format', ... 'Tag','wopt', ... 'Checked',onoff(UWPFLOW.opt.w.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig W', ... 'Label','[-W] Write solution in IEEE TAPE format', ... 'Tag','wopt', ... 'Checked',onoff(UWPFLOW.opt.W.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig y', ... 'Label','[-y] Print left e-vector of smallest |e-value|', ... 'Tag','yopt', ... 'Checked',onoff(UWPFLOW.opt.y.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig Y', ... 'Label','[-Y] Print right e-vector of smallest |e-value|', ... 'Tag','Yopt', ... 'Checked',onoff(UWPFLOW.opt.Y.status)); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwfig Z', ... 'Label','[-Z] Print normalized tangent vector', ... 'Tag','Zopt', ... 'Checked',onoff(UWPFLOW.opt.Z.status)); % Menu Preferences h1 = uimenu('Parent',h0, ... 'Label','Preferences', ... 'Tag','MenuPref'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow filename', ... 'Label','Modify input/output file name', ... 'Tag','OTV', ... 'Accelerator','e'); h2 = uimenu('Parent',h1, ... 'Callback','fm_tviewer', ... 'Label','Select Text Viewer', ... 'Tag','tvopt', ... 'Separator', 'on', ... 'Accelerator','t'); % Menu Help h1 = uimenu('Parent',h0, ... 'Label','Help', ... 'Tag','MenuHelp'); h2 = uimenu('Parent',h1, ... 'Callback','fm_uwpflow help', ... 'Label','UWPFLOW help', ... 'Accelerator','h', ... 'Tag','UWHelp'); h2 = uimenu('Parent',h1, ... 'Callback','web(''http://thunderbox.uwaterloo.ca/~claudio/software/pflow.html'');', ... 'Label','UWPFLOW website', ... 'Accelerator','w', ... 'Tag','UWLink'); % Frame h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor',Theme.color03, ... 'Position',[0.0329 0.1399 0.9394 0.8405], ... 'Style','frame', ... 'Tag','Frame1'); % List Boxes h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig B', ... 'HorizontalAlignment','left', ... 'Position',[x3 0.9199 dx 0.0339], ... 'String','[-B] Bus for fixed voltage:', ... 'Style','checkbox', ... 'Tag','Check_B', ... 'Value', UWPFLOW.opt.B.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.B.num = get(gcbo,''Value''); UWPFLOW.opt.B.num = UWPFLOW.opt.B.num(end); set(gcbo,''Value'',UWPFLOW.opt.B.num)', ... 'Enable', onoff(UWPFLOW.opt.B.status), ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'ListboxTop',UWPFLOW.opt.B.num, ... 'Max', 100, ... 'Position',[x3 0.7439 dx 0.1595], ... 'String',PQbuses, ... 'Style','listbox', ... 'Tag','Edit_B', ... 'Value',UWPFLOW.opt.B.num); dyy = 0.015; h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig f', ... 'HorizontalAlignment','left', ... 'Position',[x3 0.6835+dyy dx 0.0339], ... 'String','[-f] Bus for SF, VSF and TG:', ... 'Style','checkbox', ... 'Tag','Check_f', ... 'Value', UWPFLOW.opt.f.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.f.num = get(gcbo,''Value''); UWPFLOW.opt.f.num = UWPFLOW.opt.f.num(end); set(gcbo,''Value'',UWPFLOW.opt.f.num)', ... 'Enable', onoff(UWPFLOW.opt.f.status), ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'ListboxTop',UWPFLOW.opt.f.num, ... 'Max', 100, ... 'Position',[x3 0.5076+dyy dx 0.1595], ... 'String',PQbuses, ... 'Style','listbox', ... 'Tag','Edit_f', ... 'Value',UWPFLOW.opt.f.num); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig one', ... 'HorizontalAlignment','left', ... 'Position',[x3 0.4471+2*dyy dx 0.0339], ... 'String','[-1] Bus for test functions:', ... 'Style','checkbox', ... 'Tag','Check_one', ... 'Value', UWPFLOW.opt.one.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.one.num = get(gcbo,''Value''); UWPFLOW.opt.one.num = UWPFLOW.opt.one.num(end); set(gcbo,''Value'',UWPFLOW.opt.one.num)', ... 'Enable', onoff(UWPFLOW.opt.one.status), ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'ListboxTop',UWPFLOW.opt.one.num, ... 'Max', 100, ... 'Position',[x3 0.2712+2*dyy dx 0.1595], ... 'String',PQbuses, ... 'Style','listbox', ... 'Tag','Edit_one', ... 'Value',UWPFLOW.opt.one.num); % Popup Menus h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwpflow methods', ... 'FontName', Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.2712+2*dyy dx 0.0308], ... 'String',methods, ... 'Style','popupmenu', ... 'Tag','PopupMenuMethod', ... 'Value',UWPFLOW.method); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.305+2*dyy dx 0.0308], ... 'String','Solver method:', ... 'Style','text', ... 'Tag','StaticText12'); h1 = uicontrol('Parent', h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', '', ... 'FontName', Theme.font01, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.2712+2*dyy dx 0.0308], ... 'String',output, ... 'Style','popupmenu', ... 'Tag','PopupUWFile', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.305+2*dyy dx 0.0308], ... 'String','UWPFLOW input/output file:', ... 'Style','text', ... 'Tag','StaticText11'); % Pushbuttons h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color03, ... 'Callback','fm_uwpflow uwrun', ... 'FontWeight','bold', ... 'ForegroundColor',Theme.color09, ... 'Position',[x1 0.1576-2*dm dx 0.045+2*dm], ... 'String','Run UWPFLOW', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','close(gcf)', ... 'Position',[x3 0.1576-2*dm dx 0.045+2*dm], ... 'String','Close', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback','fm_uwpflow view', ... 'Position',[x2 0.1576-2*dm dx 0.045+2*dm], ... 'String','View Input/Output File', ... 'Tag','Pushbutton3'); % UWPFLOW Command Line h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.command = get(gcbo,''String'');', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.225 x3+dx-x1 0.0308+dm], ... 'Style','edit', ... 'String', UWPFLOW.command, ... 'Tag','EditCom'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.225+0.0308+dm dx 0.0308], ... 'String','Command Line:', ... 'Style','text', ... 'Tag','TextCom'); % Parameters (left column) h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.F.num = fval(gcbo,UWPFLOW.opt.F.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.F.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.8731 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.F.num), ... 'Tag','Edit_F'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig F', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.9199 dx 0.0339], ... 'String','[-F] Stability/sparsity [0,1]', ... 'Style','checkbox', ... 'Tag','Check_F', ... 'Value', UWPFLOW.opt.F.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.t.num = fval(gcbo,UWPFLOW.opt.t.num)', ... 'Enable', onoff(UWPFLOW.opt.t.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.7764 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.t.num), ... 'Tag','Edit_t'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig t', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.8232 dx 0.0339], ... 'String','[-t] Iteration mismatch tol.', ... 'Style','checkbox', ... 'Tag','Check_t', ... 'Value', UWPFLOW.opt.t.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.o.num = fval(gcbo,UWPFLOW.opt.o.num);', ... 'Enable', onoff(UWPFLOW.opt.o.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.6798 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.o.num), ... 'Tag','Edit_o'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig o', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.7266 dx 0.0339], ... 'String','[-o] Limit control tol.', ... 'Style','checkbox', ... 'Tag','Check_o', ... 'Value', UWPFLOW.opt.o.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.L.num = fval(gcbo,UWPFLOW.opt.L.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.L.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.5831 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.L.num), ... 'Tag','Edit_L'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig L', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.6299 dx 0.0339], ... 'String','[-L] Initial loading factor', ... 'Style','checkbox', ... 'Tag','Check_L', ... 'Value', UWPFLOW.opt.L.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.O.num = fval(gcbo,UWPFLOW.opt.O.num)', ... 'Enable', onoff(UWPFLOW.opt.O.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.4865 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.O.num), ... 'Tag','Edit_O'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig O', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x1 0.5333 dx 0.0339], ... 'String','[-O] ac/dc TEF digits [6-10]', ... 'Style','checkbox', ... 'Tag','Check_O', ... 'Value', UWPFLOW.opt.O.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.S.num = fval(gcbo,UWPFLOW.opt.S.num);', ... 'Enable', onoff(UWPFLOW.opt.S.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x1 0.3898 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.S.num), ... 'Tag','Edit_S'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig S', ... 'HorizontalAlignment','left', ... 'Position',[x1 0.4366 dx 0.0339], ... 'String','[-S] Max. loading factor [0,1]', ... 'Style','checkbox', ... 'Tag','Check_S', ... 'Value', UWPFLOW.opt.S.status); % Parameters (middle column) h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.k.num = fval(gcbo,UWPFLOW.opt.k.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.k.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.8731 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.k.num), ... 'Tag','Edit_k'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig k', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.9199 dx 0.0339], ... 'String','[-k] Loading factor increment', ... 'Style','checkbox', ... 'Tag','Check_k', ... 'Value', UWPFLOW.opt.k.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.u.num = fval(gcbo,UWPFLOW.opt.u.num)', ... 'Enable', onoff(UWPFLOW.opt.u.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.7764 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.u.num), ... 'Tag','Edit_u'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig u', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.8232 dx 0.0339], ... 'String','[-u] Reduce eq. tol. [0,0.2]', ... 'Style','checkbox', ... 'Tag','Check_u', ... 'Value', UWPFLOW.opt.u.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.U.num = fval(gcbo,UWPFLOW.opt.U.num);', ... 'Enable', onoff(UWPFLOW.opt.U.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.6798 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.U.num), ... 'Tag','Edit_U'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig U', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.7266 dx 0.0339], ... 'String','[-U] Step # for sys. red. [2,100]', ... 'Style','checkbox', ... 'Tag','Check_U', ... 'Value', UWPFLOW.opt.U.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.v.num = fval(gcbo,UWPFLOW.opt.v.num);', ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'Enable', onoff(UWPFLOW.opt.v.status), ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.5831 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.v.num), ... 'Tag','Edit_v'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig v', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.6299 dx 0.0339], ... 'String','[-v] PQ bus voltage magnitude', ... 'Style','checkbox', ... 'Tag','Check_v', ... 'Value', UWPFLOW.opt.v.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback', 'UWPFLOW.opt.z.num = fval(gcbo,UWPFLOW.opt.z.num)', ... 'Enable', onoff(UWPFLOW.opt.z.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.4865 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.z.num), ... 'Tag','Edit_z'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'Callback', 'fm_uwfig z', ... 'BackgroundColor',Theme.color02, ... 'HorizontalAlignment','left', ... 'Position',[x2 0.5333 dx 0.0339], ... 'String','[-z] Max. # of CM steps', ... 'Style','checkbox', ... 'Tag','Check_z', ... 'Value', UWPFLOW.opt.z.status); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color04, ... 'Callback','UWPFLOW.opt.two.num = fval(gcbo,UWPFLOW.opt.two.num);', ... 'Enable', onoff(UWPFLOW.opt.two.status), ... 'FontName',Theme.font01, ... 'ForegroundColor',Theme.color05, ... 'HorizontalAlignment',aligntxt, ... 'Position',[x2 0.3898 dx 0.0308+dm], ... 'Style','edit', ... 'String', num2str(UWPFLOW.opt.two.num), ... 'Tag','Edit_two'); h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'Callback', 'fm_uwfig two', ... 'HorizontalAlignment','left', ... 'Position',[x2 0.4366 dx 0.0339], ... 'String','[-2] Step # for dir. change', ... 'Style','checkbox', ... 'Tag','Check_two', ... 'Value', UWPFLOW.opt.two.status); % Banner h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'Color',Theme.color04, ... 'ColorOrder',Settings.color, ... 'Layer','top', ... 'Position',[0.0329 0.0169 0.8*0.1540 0.8*0.1371], ... 'Tag','Axes1', ... 'XColor',Theme.color02, ... 'XLim',[0.5 100.5], ... 'XLimMode','manual', ... 'XTick',[], ... 'YColor',Theme.color02, ... 'YDir','reverse', ... 'YLim',[0.5 100.5], ... 'YLimMode','manual', ... 'YTick',[], ... 'ZColor',[0 0 0]); if Settings.hostver < 8.04 h2 = image('Parent',h1, ... 'CData',fm_mat('logo_psat'), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); else h2 = image('Parent',h1, ... 'CData',flipud(fliplr(fm_mat('logo_psat'))), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); end h1 = axes('Parent',h0, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'Color',Theme.color02, ... 'ColorOrder',Settings.color, ... 'Layer','top', ... 'Position',[0.8491 0.0169 0.8*0.1540 0.8*0.1371], ... 'Tag','Axes1', ... 'XColor',Theme.color02, ... 'XLim',[0.5 100.5], ... 'XLimMode','manual', ... 'XTick',[], ... 'YColor',Theme.color02, ... 'YDir','reverse', ... 'YLim',[0.5 100.5], ... 'YLimMode','manual', ... 'YTick',[], ... 'ZColor',[0 0 0]); if Settings.hostver < 8.04 h2 = image('Parent',h1, ... 'CData',fm_mat('logo_uwpflow'), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); else h2 = image('Parent',h1, ... 'CData',flipud(fliplr(fm_mat('logo_uwpflow'))), ... 'Tag','Axes1Image1', ... 'XData',[1 101], ... 'YData',[1 101]); end h1 = uicontrol('Parent',h0, ... 'Units', 'normalized', ... 'BackgroundColor',Theme.color02, ... 'ForegroundColor', [0 0 1], ... 'FontSize', 12, ... 'FontName', 'Times', ... 'FontWeight', 'bold', ... 'FontAngle', 'italic',... 'Position',[0.2915 0.0516 0.4221 0.0355], ... 'String','PSAT-UWPFLOW Interface', ... 'Style','text', ... 'Tag','StaticText3'); if nargout > 0, fig = h0; end % --------------------------------------------------------- function output = onoff(input) if input, output = 'on'; else, output = 'off'; end % --------------------------------------------------------- function checkon(field) global UWPFLOW Fig if isfield(UWPFLOW.opt,field) a = getfield(UWPFLOW.opt,field); a.status = ~a.status; UWPFLOW.opt = setfield(UWPFLOW.opt,field,a); try % strcmp(get(gcbo,'Style'),'checkbox') set(gcbo,'Value',a.status) hdl = findobj(Fig.uwpflow,'Tag',['Edit_',field]); set(hdl,'Enable',onoff(a.status)) catch set(gcbo,'Checked',onoff(a.status)) end end
github
Sinan81/PSAT-master
sim2psat.m
.m
PSAT-master/psat-oct/psat/filters/sim2psat.m
29,948
utf_8
eaf79c62c1825a9a71b6f65fe0cb7b15
function check_model = sim2psat(varargin) % SIM2PSAT convert Simulink models into PSAT data files % % CHECK = SIM2PSAT % CHECK = 0 conversion failed % CHECK = 1 conversion completed % %see also FM_LIB, FM_SIMREP, FM_SIMSET % %Author: Federico Milano %Date: 01-Jan-2006 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2009 Federico Milano global File Fig Settings Hdl Path Theme History if ~nargin File_Data = File.data; Path_Data = Path.data; else File_Data = varargin{1}; Path_Data = varargin{2}; end if ~strcmp(Path_Data(end),filesep) Path_Data = [Path_Data,filesep]; end check_model = 1; fm_disp fm_disp('Simulink Model Conversion'); fm_disp(['Simulink File <',File_Data,'>.']); % component names % NB. 'Varname' must be the last element Compnames = {'Bus','Line','Shunt','Breaker', ... 'Fault','SW','PV','PQ','PQgen', ... 'Mn','Pl','Fl','Lines','Twt','Syn', ... 'Ind','Mot','Ltc','Thload','Tg','Exc', ... 'Pss','Oxl','Hvdc','Svc','Tcsc', ... 'Statcom','Sssc','Upfc','Mass','SSR', ... 'Tap','Demand','Supply','Rsrv','Rmpg', ... 'Rmpl','Vltn','Ypdp','Sofc','Cac','Spv','Spq', ... 'Cluster','Exload','Phs','Cswt','Dfig', ... 'Ddsg','Wind','Busfreq','Pmu','Jimma', ... 'Mixload','Pod','Areas','Regions','Varname'}; lasterr(''); for i = 1:length(Compnames), eval([Compnames{i}, ' = [];']); end tipi = length(Compnames)-1; % constants used in the component masks % ---------------------------------------------------------------- on = 1; off = 0; omega = 1; power = 2; voltage = 3; monday = 1; tuesday = 2; wednesday = 3; thursday = 4; friday = 5; saturday = 6; sunday = 7; winter_week_day = 1; winter_week_end = 2; summer_week_day = 3; summer_week_end = 4; spring_fall_week_day = 5; spring_fall_week_end = 6; measurements = 1; weibull = 2; composite = 3; mexican_hat = 4; Bus_V = 1; Line_P_from_bus = 2; Line_P_to_bus = 3; Line_I_from_bus = 4; Line_I_to_bus = 5; Line_Q_from_bus = 6; Line_Q_to_bus = 7; in = 1; out = 1; ins = 1; ous = 1; constant_voltage = 1; constant_reactance = 2; constant_power = 3; constant_line_power = 1; constant_angle = 2; SVC_control = 1; TCSC_control = 2; STATCOM_control = 3; SSSC_control = 4; UPFC_control = 5; Xc = 1; Alpha = 2; constant_admittance = 1; constant_power_flow = 2; Current_control = 1; Power_control = 2; Voltage_control = 3; % loading Simulink model % ---------------------------------------------------------------- File_Data = strrep(File_Data,'(mdl)',''); File_Data = strrep(File_Data,'.mdl',''); fm_disp('Loading Simulink Model') %cd(Path_Data); open_sys = find_system('type','block_diagram'); OpenModel = sum(strcmp(open_sys,File_Data)); if OpenModel cur_sys = get_param(File_Data,'Handle'); else localpath = pwd; cd(Path_Data) if exist(File_Data,'file') ~= 4 fm_disp(['File <',File_Data,'> is not a Simulink model.'],2) check_model = 0; return end warning('off', 'Simulink:Engine:InvalidDomainRegistrationKey'); cur_sys = load_system(File_Data); cd(localpath) end % open status bar fm_bar open % load block and mask properties % ---------------------------------------------------------------- fm_disp(' * * *') fm_disp('Check model version and blocks ...') SimUpdate(cur_sys) Settings.mv = str2num(get_param(cur_sys,'ModelVersion')); blocks = find_system(cur_sys,'Type','block'); if strcmp(get_param(cur_sys,'Open'),'on') hilite_system(cur_sys,'none') end masks = get_param(blocks,'MaskType'); nblock = length(blocks); tipi3 = 1/(tipi + 1 + 2*nblock); fm_bar([1e-3,tipi3]) fm_disp(' * * *') fm_disp('Statistics ...') vector = zeros(13,1); vector(1) = length(find_system(blocks,'Description','Connection')); vector(2) = length(find_system(blocks,'Description','Power Flow')); vector(3) = length(find_system(blocks,'Description','OPF & CPF')); vector(4) = length(find_system(blocks,'Description','Faults & Breakers')); vector(5) = length(find_system(blocks,'Description','Loads')); vector(6) = length(find_system(blocks,'Description','Machines')); vector(7) = length(find_system(blocks,'Description','ULTC')); vector(8) = length(find_system(blocks,'Description','Controls')); vector(9) = length(find_system(blocks,'Description','FACTS')); vector(10) = length(find_system(blocks,'Description','Sparse Dynamic Component')); vector(11) = length(find_system(blocks,'Description','Wind Turbines')); vector(12) = length(find_system(blocks,'Description','Measurements')); dispno(vector(1),'Connections') dispno(vector(2),'Power Flow Components') dispno(vector(3),'OPF & CPF Components') dispno(vector(4),'Faults & Breakers') dispno(vector(5),'Special Loads') dispno(vector(6),'Machines') dispno(vector(7),'Regulating Transformers') dispno(vector(8),'Controls') dispno(vector(9),'FACTS') dispno(vector(10),'Spare Dynamic Components') dispno(vector(11),'Wind Power Components') dispno(vector(12),'Measurement Components') % component data matrices % ---------------------------------------------------------------- fm_disp(' * * *') fm_disp('Definition of component data ...') kinds = zeros(length(Compnames),1); idx_old = 0; for i = 1:nblock tipo = masks{i}; idx = strmatch(tipo,Compnames,'exact'); if ~isempty(idx) kinds(idx) = kinds(idx)+1; sidx = num2str(kinds(idx)); if idx ~= idx_old idx_old = idx; fm_disp(['Data "',tipo,'.con"']) end comp_data = get_param(blocks(i),'MaskVariables'); comp_value = get_param(blocks(i),'MaskValueString'); valori = strrep(['[',comp_value,']'],'|',','); indici = comp_data; if strmatch(indici,'pxq=@1;','exact') indici = ':'; else indici = ['[',indici,']']; indici = strrep(indici,'x',':'); indici = strrep(indici,'p',''); indici = strrep(indici,'_',' '); indici = strrep(indici,'q',''); end indici = regexprep(indici,'=@([0-9]*);',' '); try eval([tipo,'(',sidx,',',indici,') = ',valori,';']); catch %[tipo,'(',sidx,',',indici,') = ',valori,';'] fm_disp(['Error: ',tipo,' block <', ... get_param(blocks(i),'Name'), ... '> has a wrong number of data.'],2) hilite_system(blocks(i),'default') eval([tipo,'(',sidx,',',indici,') = 0;']); end set_param(blocks(i),'UserData',sidx); end if ~rem(i,5), fm_bar([(i-1)*tipi3,i*tipi3]), end end % "Bus" number % ---------------------------------------------------------------- busidx = find(strcmp(masks,'Bus')); busname = get_param(blocks(busidx),'Name'); Bus_n = length(busidx); Bus(:,1) = [1:Bus_n]'; fm_disp(' * * *') fm_disp('Definition of system connections ...') for i = 1:nblock if isempty(masks{i}), continue, end if strcmp(get_param(blocks(i),'Description'),'Connection') continue end rowno = get_param(blocks(i),'UserData'); % define connections switch masks{i} case {'Exc','Tg','Mass'} Destin = {'Syn'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case {'Pss','Oxl'} Destin = {'Exc'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case 'Rmpg' Destin = {'Supply'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case 'Rmpl' Destin = ''; dst = []; posdst = []; Source = {'Demand'}; src = 1; possrc = 1; case 'Breaker' Destin = {'Bus'}; dst = 2; posdst = 2; Source = {'Line'}; src = 1; possrc = 1; case 'Pod' Destin = {'Statcom','Sssc','Svc','Upfc','Tcsc','Dfig'}; dst = 2; posdst = 2; MaskValues = get_param(blocks(i),'MaskValues'); if strcmp(MaskValues{1},'Bus_V') Source = {'Bus'}; else Source = {'Line'}; end src = 1; possrc = 1; case 'Cluster' Source = {'Cac'}; src = 1; possrc = 1; Destin = {'Exc','Svc'}; dst = 2; posdst = 2; case {'PV','SW','Supply','Rsrv','Rmpg','Vltn', ... 'SSR','Sofc','PQgen','Syn','Supply','Spv','Spq'} Destin = {'Bus'}; dst = 1; posdst = 1; Source = ''; src = []; possrc = []; case {'Line','Lines','Phs','RLC','Hvdc'} Destin = {'Bus'}; dst = 2; posdst = 2; Source = {'Bus'}; src = 1; possrc = 1; case {'Sssc','Upfc','Tcsc'} Destin = ''; dst = []; posdst = []; Source = {'Line'}; src = 1; possrc = 1; case 'Ltc' MaskValues = get_param(blocks(i),'MaskValues'); if strcmp(MaskValues{3},'3') Destin = {'Bus'}; dst = 3; posdst = 2; Source = {'Bus'}; src = [1 2]; possrc = [15 1]; else Destin = {'Bus'}; dst = 2; posdst = 2; Source = {'Bus'}; src = 1; possrc = 1; end case {'Cswt','Dfig','Ddsg'} Destin = {'Bus'}; dst = 2; posdst = 1; Source = {'Wind'}; src = 1; possrc = 2; case 'Twt' Destin = {'Bus'}; dst = [2 3]; posdst = [2 3]; Source = {'Bus'}; src = 1; possrc = 1; %case {'SAE1','SAE2','SAE3'} % Source = {'Bus'}; % src = [1 2]; possrc = [1 2]; % Destin = ''; % dst = []; posdst = []; case {'Ypdp','Wind','Varname'} Source = ''; src = []; possrc = []; Destin = ''; dst = []; posdst = []; case {'Areas','Regions'} Source = ''; src = []; possrc = []; MaskValues = get_param(blocks(i),'MaskValues'); if strcmp(MaskValues{1},'1') Destin = {'Bus'}; dst = 1; posdst = 2; else Destin = ''; dst = []; posdst = []; end otherwise Destin = ''; dst = []; posdst = []; Source = {'Bus'}; src = 1; possrc = 1; end % find connections for j = 1:length(dst) block2_handle = SeekDstBlock(blocks(i),Destin,dst(j)); busno = get_param(block2_handle,'UserData'); eval([masks{i},'(',rowno,',',num2str(posdst(j)),') = ',busno,';']); if strcmp(masks(i),'Cluster') switch get_param(block2_handle,'MaskType') case 'Exc', ctype = '1'; case 'Svc', ctype = '2'; end eval([masks{i},'(',rowno,',3) = ',ctype,';']); end if strcmp(masks(i),'Pod') switch get_param(block2_handle,'MaskType') case 'Svc', ctype = '1'; case 'Tcsc', ctype = '2'; case 'Statcom', ctype = '3'; case 'Sssc', ctype = '4'; case 'Upfc', ctype = '5'; case 'Dfig', ctype = '6'; end eval([masks{i},'(',rowno,',4) = ',ctype,';']); end end for j = 1:length(src) block2_handle = SeekSrcBlock(blocks(i),Source,src(j)); busno = get_param(block2_handle,'UserData'); eval([masks{i},'(',rowno,',',num2str(possrc(j)),') = ',busno,';']); end fm_bar([(nblock+i-1)*tipi3,(nblock+i)*tipi3]) end fm_disp(' * * *') % writing data file idx1 = strmatch('Definition of component data ...',History.text); idx2 = strmatch('Definition of system connections ...',History.text); idx3 = strmatch('Error:',History.text); if isempty(idx3), idx3 = 0; end if idx3(end) > idx1(end) if idx3(end) > idx2(end), message = 'Simulink model is not well-formed (check links).'; end if find(idx3 < idx2(end) & idx3 > idx1(end)), message = ['Component data are not well-formed (check ' ... 'masks).']; end else File_Data = [File_Data,'_mdl']; [fid, message] = fopen([Path_Data,File_Data,'.m'], 'wt'); end if ~isempty(message), if strcmp(message, ... ['Sorry. No help in figuring out the problem ...']), fm_disp(['Most likely the folder "',Path_Data, ... '" is read only. Try to change the permission.']) else fm_disp(['Failed conversion from Simulink model: ',message],2) end if ishandle(Fig.main) set(Fig.main,'Pointer','arrow'); delete(Hdl.bar); Hdl.bar = 0; set(Hdl.frame,'Visible','on'); set(Hdl.text,'Visible','on'); end check_model = 0; return else fm_disp('Writing Data File',1) end fm_bar([(2*nblock)*tipi3,(2*nblock+1)*tipi3]) for j = 1:length(Compnames)-1 values = eval(Compnames{j}); if ~isempty(values) count = fprintf(fid,'%s.con = [ ... \n',Compnames{j}); for i = 1:length(values(:,1)) count = fprintf(fid,[' ',regexprep(num2str(values(i,:)),'\s*',' '),';\n']); end count = fprintf(fid,' ];\n\n'); end fm_bar([(2*nblock+j-1)*tipi3,(2*nblock+j)*tipi3]) end % count = fprintf(fid, 'Bus.names = {... \n '); % for i = 1:Bus_n-1 % namebus = strrep(busname{i,1},char(10),' '); % count = fprintf(fid, ['''',namebus,'''; ']); % if rem(i,5) == 0; count = fprintf(fid,'\n '); end % end % if iscell(busname) % namebus = strrep(busname{length(busname),1},char(10),' '); % count = fprintf(fid, ['''',namebus,'''};\n\n']); % else % namebus = strrep(busname,char(10),' '); % count = fprintf(fid, ['''',namebus,'''};\n\n']); % end WriteNames(fid,'Bus',busname); areaidx = find(strcmp(masks,'Areas')); areaname = get_param(blocks(areaidx),'Name'); WriteNames(fid,'Areas',areaname); zoneidx = find(strcmp(masks,'Regions')); zonename = get_param(blocks(zoneidx),'Name'); WriteNames(fid,'Regions',zonename); % print indexes of variables to be plotted if ~isempty(Varname) count = fprintf(fid, 'Varname.idx = [... \n'); nidx = length(Varname); count = fprintf(fid,'%5d; %5d; %5d; %5d; %5d; %5d; %5d;\n',Varname); if rem(nidx,7) ~= 0, count = fprintf(fid,'\n'); end count = fprintf(fid,' ];\n'); end % closing data file count = fclose(fid); exist(File_Data); % closing Simulink model if ~OpenModel && ~strcmp(get_param(cur_sys,'Dirty'),'on') close_system(cur_sys); end fm_disp(['Construction of Data File <',File_Data,'.m> completed.']) % close status bar fm_bar close % last operations % cd(Path.local); if Settings.beep, beep, end if ~nargin, File.data = [File_Data(1:end-4),'(mdl)']; end %------------------------------------------------------------------ function dispno(num,msg) %------------------------------------------------------------------ if num, fm_disp([msg,': #',num2str(num),'#']), end %------------------------------------------------------------------ function block_name = MaskType(block_handle) %------------------------------------------------------------------ block_name = get_param(block_handle,'MaskType'); if isempty(block_name) block_name = get_param(block_handle,'BlockType'); end if isempty(block_name) hilite_system(block_handle) block_name = 'Error'; return end if iscell(block_name) block_name = block_name{1}; end %------------------------------------------------------------------ function hdl2 = SeekDstBlock(hdl1,name2,pos) %------------------------------------------------------------------ ports = get_param(hdl1,'PortConnectivity'); if length(ports) < pos SimWarnMsg(hdl1,'has the wrong number of ports') hdl2 = hdl1; % to avoid errors in evaluating UserData return end handles = [ports.DstBlock]; try idx = find(strcmp({ports.Type},'RConn1')); if isempty(idx), idx = pos; end if idx(pos) ~= pos hdl2 = ports(idx(pos)).DstBlock; else hdl2 = handles(pos); end catch hdl2 = ports(pos).DstBlock; end hdl0 = hdl1; while 1 switch MaskType(hdl2) case name2 break case 'Outport' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).DstBlock; case 'PMIOPort' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).DstBlock; case 'SubSystem' ports = get_param(hdl2,'PortConnectivity'); port_no = num2str(find([ports(:).SrcBlock] == hdl1)); if isempty(port_no) port_no = num2str(find([ports(:).DstBlock] == hdl1)); end hdl0 = hdl2; hdl2 = find_system(hdl2,'SearchDepth',1,'Port',port_no); case 'Goto' tag = get_param(hdl2,'GotoTag'); name = find_system(gcs,'BlockType','From','GotoTag',tag); from = get_param(name{1},'Handle'); ports = get_param(from,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(1).DstBlock; case 'Link' ports = get_param(hdl2,'PortConnectivity'); if sum(strcmp(MaskType(hdl1),{'Pod','Cluster'})) if strcmp(ports(3).DstBlock,'Bus') hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Input Port else hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port end elseif strcmp(MaskType(hdl0),MaskType(ports(2).DstBlock)) hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port else hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Input Port end case 'Line' switch MaskType(hdl1) case {'Breaker','Upfc','Tcsc','Sssc'} hdl0 = hdl2; hdl2 = SeekSrcBlock(hdl1,'Bus',1); otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) end break case {'Breaker','Sssc','Upfc','Tcsc','Mass'} ports = get_param(hdl2,'PortConnectivity'); hdl_temp = hdl0; hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Output Port if hdl2 == hdl_temp hdl2 = ports(1).DstBlock; % Output Port end case 'Link2' ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port case 'Error' SimWarnMsg(hdl1,'is badly connected') hdl0 = hdl2; hdl2 = hdl1; % to avoid errors in evaluating UserData break otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) break end end %------------------------------------------------------------------ function hdl2 = SeekSrcBlock(hdl1,name2,pos) %------------------------------------------------------------------ ports = get_param(hdl1,'PortConnectivity'); if length(ports) < pos SimWarnMsg(hdl1,'has the wrong number of ports') hdl2 = hdl1; % to avoid errors in evaluating UserData return end switch ports(pos).Type case {'1','enable'} hdl2 = ports(pos).SrcBlock; otherwise hdl2 = ports(pos).DstBlock; end hdl0 = hdl1; while 1 switch MaskType(hdl2) case name2 break case 'Inport' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).SrcBlock; case 'PMIOPort' port_no = str2num(get_param(hdl2,'Port')); ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(port_no).DstBlock; case 'SubSystem' ports = get_param(hdl2,'PortConnectivity'); port_no = num2str(find([ports(:).DstBlock] == hdl1)); hdl0 = hdl2; hdl2 = find_system(hdl2,'SearchDepth',1,'Port',port_no); case 'From' tag = get_param(hdl2,'GotoTag'); name = find_system(gcs,'BlockType','Goto','GotoTag',tag) goto = get_param(name{1},'Handle'); ports = get_param(goto,'PortConnectivity'); hdl0 = hdl2; hdl2 = ports(1).SrcBlock; case 'Link' ports = get_param(hdl2,'PortConnectivity'); if strcmp(MaskType(hdl0),MaskType(ports(2).DstBlock)) hdl0 = hdl2; hdl2 = ports(3).DstBlock; % Output Port else hdl0 = hdl2; hdl2 = ports(2).DstBlock; % Input Port end case 'Bus' switch MaskType(hdl1) case {'Breaker','Sssc','Upfc','Tcsc'} hdl0 = hdl2; hdl2 = SeekDstBlock(hdl1,'Line',2); otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) end break case {'Breaker','Sssc','Upfc','Tcsc'} ports = get_param(hdl2,'PortConnectivity'); hdl_temp = hdl0; hdl0 = hdl2; hdl2 = ports(1).DstBlock; % Output Port if hdl2 == hdl_temp hdl2 = ports(2).DstBlock; % Output Port end case 'Link2' ports = get_param(hdl2,'PortConnectivity'); hdl0 = hdl2; if strcmp(MaskType(hdl1),'Pod') if strcmp(MaskType(ports(2).DstBlock),name2) hdl2 = ports(2).DstBlock; % Input Port break elseif strcmp(MaskType(ports(3).DstBlock),name2) hdl2 = ports(3).DstBlock; % Output Port break else % try to follow one path (50% likely to succeed) hdl2 = ports(3).DstBlock; % Output Port end else hdl2 = ports(2).DstBlock; % Input Port end case 'Error' SimWarnMsg(hdl1,'is badly connected') hdl0 = hdl2; hdl2 = hdl1; % to avoid errors in evaluating UserData break otherwise SimWarnMsg(hdl1,'cannot be connected to',hdl2) break end end %------------------------------------------------------------------ function SimWarnMsg(varargin) %------------------------------------------------------------------ handle1 = varargin{1}; msg = varargin{2}; hilite_system(handle1,'default') name1 = get_param(handle1,'Name'); if nargin == 2 fm_disp(['Error: Block <',name1,'> ',msg,'.']) elseif nargin == 3 handle2 = varargin{3}; name2 = get_param(handle2,'Name'); fm_disp(['Error: Block <',name1,'> ',msg,' block <',name2,'>.']) end %------------------------------------------------------------------ function WriteNames(fid,type,names) %------------------------------------------------------------------ if isempty(names), return, end n = length(names); count = fprintf(fid, [type,'.names = {... \n ']); for i = 1:n-1 name = strrep(names{i,1},char(10),' '); count = fprintf(fid, ['''',name,'''; ']); if rem(i,5) == 0; count = fprintf(fid,'\n '); end end if iscell(names) name = strrep(names{n,1},char(10),' '); count = fprintf(fid, ['''',name,'''};\n\n']); else name = strrep(names,char(10),' '); count = fprintf(fid, ['''',name,'''};\n\n']); end %------------------------------------------------------------------ function SimUpdate(sys) %------------------------------------------------------------------ global Settings sys = getfullname(sys); hilite_system(sys,'none') block = find_system(sys,'Type','block'); mask = get_param(block,'MaskType'); nblock = length(block); % check if all blocks belong to the PSAT Library Tags = get_param(block,'Tag'); BlockTypes = get_param(block,'BlockType'); idx = ones(nblock,1); idx(strmatch('PSATblock',Tags,'exact')) = 0; idx(strmatch('SubSystem',BlockTypes,'exact')) = 0; idx(strmatch('PMIOPort',BlockTypes,'exact')) = 0; if sum(idx) idx = find(idx); fm_disp(fm_strjoin('* * Warning: Block <',get_param(block(idx),'Name'), ... '> does not belong to the PSAT Simulink Library.')) Settings.ok = 0; uiwait(fm_choice(['Some blocks do not seem to belong to the ', ... 'PSAT library, but could be old blocks. ', ... 'Do you want to fix them?'])) if Settings.ok for iii = 1:length(idx) blocktype = mask{idx(iii)}; if isempty(blocktype) blocktype = get_param(block{idx(iii)},'BlockType'); end switch blocktype case {'Bus','Link','Goto','From'} prop = 'Connection'; case {'Supply','Demand','Rmpg','Rrsv','Vltn','Rmpl','Ypdp'} prop = 'OPF & CPF'; case {'Breaker','Fault'} prop = 'Faults & Breakers'; case 'Busfreq' prop = 'Measurements'; case {'Mn','Pl','Thload','Fl','Exload'} prop = 'Loads'; case {'Syn','Ind','Mot'} prop = 'Machines'; case {'Ltc','Tap'} prop = 'ULTC'; case 'Phs' prop = 'Phase Shifter'; case {'Tg','Exc','Cac','Cluster','Pss','Oxl'} prop = 'Controls'; case {'Statcom','Upfc','Svc','Hvdc','Tcsc','Sssc'} prop = 'FACTS'; case {'Dfig','Cswt','Ddsg'} prop = 'Wind Turbines'; case {'Sofc','SSR','RLC','Mass','Spv','Spq'} prop = 'Sparse Dynamic Component'; %case {'SAE1','SAE2','SAE3'} % prop = 'SAE'; otherwise prop = 'Power Flow'; end set_param(block{idx(iii)}, ... 'Tag','PSATblock', ... 'Description',prop) end save_system(sys); end else fm_disp(' ') fm_disp('* * All blocks belong to the PSAT-Simulink Library.') end % check for old models slackbus = find_system(sys,'MaskType','SW'); ports = get_param(slackbus,'Ports'); if isempty(ports) fm_disp('* * * Error: No Slack bus found!') pvbus = find_system(sys,'MaskType','PV'); ports = get_param(pvbus,'Ports'); end if isempty(ports) check = 1; fm_disp('* * Error: No connections found!') elseif iscell(ports) check = sum(ports{1}); elseif isnumeric(ports) check = sum(ports); end % check if model needs to be updated if ~check disp(' ') fm_disp('* * Warning: The model refers to an old PSAT-Simulink') fm_disp(' library. PSAT will try to update models.') disp(' ') Settings.ok = 0; uiwait(fm_choice(['The model refers to an old PSAT-Simulink ' ... 'library. Update?'],1)) if ~Settings.ok, return, end else return end load_system('fm_lib'); open_system(sys); for i = 1:nblock % fix source block if it has changed try source = get_param(block{i},'SourceBlock'); switch source case 'fm_lib/Power Flow/Transf5' set_param(block{i},'SourceBlock','fm_lib/Power Flow/Twt') case ['fm_lib/Wind',char(10),'Turbines/Cswt1'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Cswt']) case ['fm_lib/Wind',char(10),'Turbines/Dfig1'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Ddsg']) case ['fm_lib/Wind',char(10),'Turbines/Dfig2'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Dfig']) case ['fm_lib/Wind',char(10),'Turbines/Wind1'] set_param(block{i},'SourceBlock',['fm_lib/Wind',char(10),'Turbines/Wind']) case 'fm_lib/Power Flow/Extra Line' set_param(block{i},'SourceBlock','fm_lib/Power Flow/Lines') case 'fm_lib/Power Flow/PQ1' set_param(block{i},'SourceBlock','fm_lib/Power Flow/PQgen') case 'fm_lib/Machines/Gen' set_param(block{i},'SourceBlock','fm_lib/Machines/Syn') case 'fm_lib/ULTC/LTC' set_param(block{i},'SourceBlock','fm_lib/ULTC/Ltc') case 'fm_lib/ULTC/OLTC' set_param(block{i},'SourceBlock','fm_lib/ULTC/Tap') case 'fm_lib/ULTC/PHS' set_param(block{i},'SourceBlock','fm_lib/ULTC/Phs') case 'fm_lib/Others/SOFC' set_param(block{i},'SourceBlock','fm_lib/Others/Sofc') case 'fm_lib/Others/SSR' set_param(block{i},'SourceBlock','fm_lib/Others/Ssr') case 'fm_lib/Measurements/SPV' set_param(block{i},'SourceBlock','fm_lib/Others/Spv') case 'fm_lib/Measurements/SPQ' set_param(block{i},'SourceBlock','fm_lib/Others/Spq') case 'fm_lib/Measurements/PMU' set_param(block{i},'SourceBlock','fm_lib/Measurements/Pmu') case 'fm_lib/Loads/FDL' set_param(block{i},'SourceBlock','fm_lib/Loads/Fl') case 'fm_lib/Loads/LRL' set_param(block{i},'SourceBlock','fm_lib/Loads/Exload') case 'fm_lib/Loads/TCL' set_param(block{i},'SourceBlock','fm_lib/Loads/Thload') case 'fm_lib/Loads/Mixed' set_param(block{i},'SourceBlock','fm_lib/Loads/Mixload') case 'fm_lib/Loads/VDL' set_param(block{i},'SourceBlock','fm_lib/Loads/Mn') case 'fm_lib/Loads/ZIP' set_param(block{i},'SourceBlock','fm_lib/Loads/Pl') case 'fm_lib/FACTS/HVDC' set_param(block{i},'SourceBlock','fm_lib/FACTS/Hvdc') case 'fm_lib/FACTS/SSSC' set_param(block{i},'SourceBlock','fm_lib/FACTS/Sssc') case 'fm_lib/FACTS/SVC (1)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Svc') case 'fm_lib/FACTS/SVC (2)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Svc2') case 'fm_lib/FACTS/StatCom' set_param(block{i},'SourceBlock','fm_lib/FACTS/Statcom') case 'fm_lib/FACTS/TCSC (1)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Tcsc') case 'fm_lib/FACTS/TCSC (2)' set_param(block{i},'SourceBlock','fm_lib/FACTS/Tcsc2') case 'fm_lib/FACTS/UPFC' set_param(block{i},'SourceBlock','fm_lib/FACTS/Upfc') case 'fm_lib/Connections/Link' set_param(block{i},'SourceBlock','fm_lib/Connections/Link1') case 'fm_lib/OPF & CPF/RMPG' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Rmpg') case 'fm_lib/OPF & CPF/RMPL' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Rmpl') case 'fm_lib/OPF & CPF/RSRV' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Rsrv') case 'fm_lib/OPF & CPF/VLTN' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Vltn') case 'fm_lib/OPF & CPF/YPDP' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Ypdp') case 'fm_lib/OPF & CPF/YPDP1' set_param(block{i},'SourceBlock','fm_lib/OPF & CPF/Ypdp1') case 'fm_lib/Controls/AVR' set_param(block{i},'SourceBlock','fm_lib/Controls/Exc') case 'fm_lib/Controls/TG' set_param(block{i},'SourceBlock','fm_lib/Controls/Tg') case 'fm_lib/Controls/SSCL' set_param(block{i},'SourceBlock','fm_lib/Controls/Pod') case 'fm_lib/Controls/OXL' set_param(block{i},'SourceBlock','fm_lib/Controls/Oxl') case 'fm_lib/Controls/PSS' set_param(block{i},'SourceBlock','fm_lib/Controls/Pss') case 'fm_lib/Controls/CAC' set_param(block{i},'SourceBlock','fm_lib/Controls/Cac') case 'fm_lib/Controls/Shaft' set_param(block{i},'SourceBlock','fm_lib/Others/Mass') end mask{i} = get_param(block{i},'MaskType'); catch % the source block has not changed end switch mask{i} case {'Bus','Link','Line','Lines','Breaker','Twt' ... 'Phs','Tcsc','Sssc','Upfc','Hvdc','Dfig', ... 'Cswt','Ddsg','RLC','PV','SW','PQgen','Spv','Spq', ... 'Rmpg','Rsrv','Vltn','Wind','Sofc','Ssr', ... 'PQ','Shunt','Rmpl','Fault','Mn','Pl','Ind','Mot', ... 'Fl','Exload','Mixload','Thload','Jimma','Tap', ... 'Svc','Statcom','Busfreq','Pmu','Supply', ... 'Demand','Syn','Ltc','SAE1','SAE2','SAE3', ... 'Exc','Tg','Sscl','Cac','Oxl','Pss','Cluster'} cloneblock(block{i},sys) end end lines = find_system(sys,'FindAll','on','type','line'); for i = 1:length(lines) points = get_param(lines(i),'Points'); parent = get_param(lines(i),'Parent'); delete_line(parent,points(1,:)); try add_line(parent,points); catch fm_disp(['* * Connection line ',num2str(i),' could not be replaced.']) end end uiwait(fm_choice('Now please take a moment to doublecheck connections...',2)) fm_disp(' ') fm_disp(['* * Update of model <',sys,'> completed.'])
github
Sinan81/PSAT-master
psat2epri.m
.m
PSAT-master/psat-oct/psat/filters/psat2epri.m
10,049
utf_8
fd2ab45d2c3ab7faff9a51b6be3ac9d2
function check = psat2epri(filename, pathname) % PSAT2EPRI converts PSAT data file into EPRI Data Format % % CHECK = PSAT2EPRI(FILENAME,PATHNAME) % FILENAME name of the file to be converted % PATHNAME path of the file to be converted % % CHECK = 1 conversion completed % CHECK = 0 problem encountered (no data file created) % %Author: Federico Milano %Date: 06-Oct-2003 %Version: 1.0.0 % %E-mail: [email protected] %Web-site: faraday1.ucd.ie/psat.html % % Copyright (C) 2002-2009 Federico Milano global DAE Varname Settings DAE_old = DAE; Varname_old = Varname; Settings_old = Settings; if strcmp(pathname(end),filesep) pathname = pathname(1:end-1); end if ~strcmp(pathname,pwd) cd(pathname) end fm_disp fm_disp(['Opening PSAT file "',filename,'"...']) % General Settings % ----------------------------------------------------------- check = 1; b128 = [blanks(128),'\n']; b12 = blanks(12); % Defining local data structures % ----------------------------------------------------------- Bus = BUclass; Twt = TWclass; Line = LNclass; Shunt = SHclass; SW = SWclass; PV = PVclass; PQ = PQclass; PQgen = PQclass; Ltc = LTclass; Phs = PHclass; % Reading Data from PSAT Data File % ----------------------------------------------------------- a = exist(filename); if a == 2, eval(filename(1:end-2)) else, fm_disp(['File "',filename,'" not found or not an m-file'],2) check = 0; return end % Completing data settings % ----------------------------------------------------------- Bus = setup_bus(Bus); Line = setup_line(Line,Bus); Twt = setup_twt(Twt,Bus,Line); Shunt = setup_shunt(Shunt,Bus); PV = setup_pv(PV,Bus); SW = setup_sw(SW,Bus,PV); PQ = setup_pq(PQ,Bus); PQgen = setup_pq(PQgen,Bus); PQ = addgen_pq(PQ,PQgen,Bus); Ltc = setup_ltc(Ltc,Bus); Phs = setup_phs(Phs,Bus); % Opening File % ----------------------------------------------------------- newfile = [filename(1:end-2),'.wsc']; fm_disp(['Writing WSCC file "',newfile,'"...']) fid = fopen([pathname,filesep, newfile], 'wt'); comment = ['C\nC',repmat('*',1,79),'\nC\n']; count = fprintf(fid,comment); % Header and Title % ----------------------------------------------------------- count = fprintf(fid,'HDG\n'); count = fprintf(fid,['PSAT ARCHIVE\n']); count = fprintf(fid,[num2str(Bus.n),'-Bus ', ... num2str(Line.n),'-Line System\n']); count = fprintf(fid,[date,'\n']); count = fprintf(fid,'BAS\n'); count = fprintf(fid,comment); % Bus Data % ----------------------------------------------------------- % Section Start card idxPV = []; idxPQ = []; idxSW = []; idxSH = []; Busnames = cell(Bus.n,1); % Scan each bus for data for i = 1:Bus.n % the following lines ensure that bus names % are unique and with no repetitions busname = Bus.names{i}; if length(busname) > 8, busname = busname([1:8]); end idx = strmatch(busname,Bus.names); if length(idx) > 1 idx = find(idx == i); nn = length(num2str(idx)); busname([(end-idx+1):end]) = num2str(idx); end busname = [busname,blanks(8)]; busname = busname([1:8]); Busnames{i,1} = busname; count = fprintf(fid,'B'); idxPV = findbus_pv(PV,i); idxPQ = findbus_pq(PQ,i); idxSW = findbus_sw(SW,i); if ~isempty(Shunt.con) idxSH = find(Shunt.bus == i); end % Bus type if ~isempty(idxSW) count = fprintf(fid,'S '); slackname = busname; slackkV = Bus.con(i,2); slackang = SW.con(idxSW,5); elseif ~isempty(idxPV) if PV.con(idxPV,6) == 0 && PV.con(idxPV,7) == 0 count = fprintf(fid,'E '); else count = fprintf(fid,'Q '); end elseif ~isempty(idxPQ) if PQ.con(idxPQ,6) == 0 && PQ.con(idxPQ,7) == 0 count = fprintf(fid,' '); else count = fprintf(fid,'V '); PQ.con(idxPQ,4) = PQ.con(idxPQ,4); PQ.con(idxPQ,5) = PQ.con(idxPQ,5); end else count = fprintf(fid,' '); end % Bus name, voltage rate and zone kV = Bus.con(i,2); count = fprintf(fid,['%s',tr(kV,4),' '],busname,kV); % Load powers if ~isempty(idxPQ) P = PQ.con(idxPQ,4)*PQ.con(idxPQ,2); Q = PQ.con(idxPQ,5)*PQ.con(idxPQ,2); count = fprintf(fid,[tr(P,5),tr(Q,5)],P,Q); else count = fprintf(fid,blanks(10)); end % Shunts if ~isempty(idxSH) G = Shunt.con(idxSH,5)*Shunt.con(idxSH,2)/(Shunt.con(idxSH,3)^2); B = Shunt.con(idxSH,6)*Shunt.con(idxSH,2)/(Shunt.con(idxSH,3)^2); count = fprintf(fid,[tr(G,4),tr(B,4)],G,B); else count = fprintf(fid,blanks(8)); end % Generator powers and limits if ~isempty(idxPV) PM = PV.con(idxPV,2); Pg = PV.con(idxPV,4)*PV.con(idxPV,2); count = fprintf(fid,[tr(PM,4),tr(Pg,5)],PM,Pg); if PV.con(idxPV,6) ~= 0 || PV.con(idxPV,7) ~= 0 QM = PV.con(idxPV,6)*PV.con(idxPV,2); Qm = PV.con(idxPV,7)*PV.con(idxPV,2); if QM < Qm dummy = QM; QM = Qm; Qm = dummy; end count = fprintf(fid,[tr(QM,5),tr(Qm,5)],QM,Qm); else count = fprintf(fid,blanks(10)); end elseif ~isempty(idxSW) PM = SW.con(idxSW,2); Pg = SW.con(idxSW,10)*SW.con(idxSW,2); count = fprintf(fid,[tr(PM,4),tr(Pg,5)],PM,Pg); if SW.con(idxSW,6) ~= 0 || SW.con(idxSW,7) ~= 0 QM = SW.con(idxSW,6)*SW.con(idxSW,2); Qm = SW.con(idxSW,7)*SW.con(idxSW,2); if QM < Qm dummy = QM; QM = Qm; Qm = dummy; end count = fprintf(fid,[tr(QM,5),tr(Qm,5)],QM,Qm); else count = fprintf(fid,blanks(10)); end else count = fprintf(fid,blanks(19)); end % Desired or maximum voltage if ~isempty(idxPV) count = fprintf(fid,'%-4.2f',PV.con(idxPV,5)); elseif ~isempty(idxSW) count = fprintf(fid,'%-4.2f',SW.con(idxSW,4)); elseif ~isempty(idxPQ) if PQ.con(idxPQ,6) ~= 0 count = fprintf(fid,'%-4.2f',PQ.con(idxPQ,6)); else count = fprintf(fid,blanks(4)); end else count = fprintf(fid,blanks(4)); end % Minimum voltage if ~isempty(idxPQ) if PQ.con(idxPQ,7) ~= 0 count = fprintf(fid,'%-4.2f',PQ.con(idxPQ,7)); else count = fprintf(fid,blanks(4)); end else count = fprintf(fid,blanks(4)); end % Remote name, kV and %Q are not Used by PSAT % ... % End of line count = fprintf(fid,'\n'); end count = fprintf(fid,comment); % Line and transformer data % ----------------------------------------------------------- % Scan each line for data for i = 1:Line.n m = Line.con(i,1); n = Line.con(i,2); if Line.con(i,7) count = fprintf(fid,'T '); else count = fprintf(fid,'L '); end count = fprintf(fid,'%s',Busnames{m}); count = fprintf(fid,tr(Bus.con(m,2),4),Bus.con(m,2)); count = fprintf(fid,' %s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); if Line.con(i,7) In = Line.con(i,3); else In = Line.con(i,3)*1e3/Line.con(i,4)/sqrt(3); end count = fprintf(fid,[' ',tr(In,4)],In); R = Line.con(i,8); X = Line.con(i,9); B = Line.con(i,10)/2; count = fprintf(fid,' %-6.4f%-6.4f%-6.4f%-6.4f',R,X,0.0,B); if Line.con(i,7) if Line.con(i,11) T = Line.con(i,11)*Line.con(i,4); count = fprintf(fid,'%-5.2f',T); T = Line.con(i,4)/Line.con(i,7); count = fprintf(fid,'%-5.2f',T); end else if Line.con(i,6) % conversion to miles L = Line.con(i,6)*0.621371; count = fprintf(fid,tr(L,4),L); end end count = fprintf(fid,'\n'); end % End line data count = fprintf(fid,comment); % Regulating Transformer Data % ----------------------------------------------------------- for i = 1:Ltc.n switch Ltc.con(i,16) case 1, count = fprintf(fid,'R '); case 2, count = fprintf(fid,'RQ '); case 3, count = fprintf(fid,'R '); end m = Ltc.bus1(i); n = Ltc.bus2(i); k = Ltc.busc; count = fprintf(fid,'%s',Busnames{m}); count = fprintf(fid,tr(Bus.con(m,2),4),Bus.con(m,2)); count = fprintf(fid,' %s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); count = fprintf(fid,'%s',Busnames{k}); count = fprintf(fid,tr(Bus.con(k,2),4),Bus.con(k,2)); count = fprintf(fid,'%-5.2f%-5.2f', ... Ltc.con(i,9)*Bus.con(m,2), ... Ltc.con(i,10)*Bus.con(m,2)); if Ltc.con(i,11) ntap = (Ltc.con(i,9)-Ltc.con(i,10))/Ltc.con(i,11); else ntap = 11; end count = fprintf(fid,tr(ntap,2),ntap); if Ltc.con(i,16) == 2 count = fprintf(fid,tr(Ltc.con(i,12),5),Ltc.con(i,12)); end end for i = 1:Phs.n count = fprintf(fid,'RP '); m = Phs.bus1(i); n = Phs.bus2(i); count = fprintf(fid,'%s',Busnames{m}); count = fprintf(fid,tr(Bus.con(m,2),4),Bus.con(m,2)); count = fprintf(fid,' %s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); count = fprintf(fid,'%s',Busnames{n}); count = fprintf(fid,tr(Bus.con(n,2),4),Bus.con(n,2)); count = fprintf(fid,'%-5.2f%-5.2f', ... Phs.con(i,13)*180/pi, ... Phs.con(i,14)*180/pi); count = fprintf(fid,'%d',11); count = fprintf(fid,tr(Phs.con(i,10),5),Phs.con(i,10)); end if Ltc.n || Phs.n % End of regulating transformer data count = fprintf(fid,comment); end % Area Data % ----------------------------------------------------------- % ... PSAT does not currently support areas ... % Solution control data % ----------------------------------------------------------- count = fprintf(fid,['SOL',blanks(20)]); count = fprintf(fid,'%-5i ',Settings.lfmit); count = fprintf(fid,'%s',slackname); count = fprintf(fid,tr(slackkV,4),slackkV); count = fprintf(fid,' %-10.4f\n',slackang); % Closing the file % ----------------------------------------------------------- count = fprintf(fid,'ZZ\n'); count = fprintf(fid,'END\n'); fclose(fid); DAE = DAE_old; Varname = Varname_old; Settings = Settings_old; fm_disp('Conversion completed.') if Settings.beep, beep, end % ----------------------------------------------------------- function string = tr(value,n) threshold = 10^(n-2); if value >= threshold || value < 0 string = '0'; else string = '1'; end string = ['%-',num2str(n),'.',string,'f'];
github
haller-group/Closed-Null-Geodesics-2D-master
add_path.m
.m
Closed-Null-Geodesics-2D-master/add_path.m
644
utf_8
b693c741666d3c95b8f19581f1d83c7c
%------------------------------------Set path function add_path fp = mfilename('fullpath'); rootdir = fileparts(fp); p{1} = fullfile(rootdir,'data'); p{2} = fullfile(rootdir,'doc'); p{3} = fullfile(rootdir,'Main'); p{4} = fullfile(rootdir,'Subfunctions'); for i = 1:4 addpath(rootdir,p{i}); end %------------------------------------ fprintf('----------------------------*---------------------------------\n'); fprintf('data,...doc,...Main,...Subfunctions,...All paths have been added'); fprintf('\n') fprintf('----------------------------*---------------------------------\n'); end
github
haller-group/Closed-Null-Geodesics-2D-master
PlotOutmost.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/PlotOutmost.m
2,786
utf_8
c4ea33d3292589c47e67d3f2ecedd59a
% function PlotOutmost(xLcOutM,yLcOutM,LamLcOutM,lamV,x_g,y_g,lam2) % Input arguments: % xLcOutM : x-component of the outermost closed null-geodesics % yLcOutM : x-component of the outermost closed null-geodesics % LamLcOutM : \lambda values of the outermost closed null-geodesics % lamV,lamV,x_g,y_g,lam2 : see step 1 %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function PlotOutmost(xLcOutM,yLcOutM,LamLcOutM,lamV,x_g,y_g,lam2) if ~isempty(LamLcOutM) % If there are closed null-geodesics % Colormap encoding different \lambda values cmap = jet(length(lamV)); % Plot properties AxthicksFnt = 15; fontsizeaxlab = 15; % Initialize the figure with the FTLE plot figure('units','normalized','outerposition',[0 0 .5 .5]); imagesc(x_g,y_g,log(lam2)/30/2);shading interp set(gca,'FontSize',AxthicksFnt,'fontWeight','normal') hold on set(gca,'YDir','normal') set(gcf,'color','w'); axis equal xlabel('$$Lon [^{\circ}]$$','Interpreter','latex','FontWeight','bold','FontSize',fontsizeaxlab); ylabel('$$Lat [^{\circ}]$$','Interpreter','latex','FontWeight','bold','FontSize',fontsizeaxlab); axis equal tight colormap(gca,'gray') hhF=colorbar(gca); hhF.Location='westOutside'; hhF.FontSize=fontsizeaxlab; set(get(hhF,'xlabel'),'string','$$FTLE$$','Interpreter','latex','FontWeight','normal'); % Plot outermost Closed null-geodesics for kkmuv=1:1:length(LamLcOutM) Lamidx=find(lamV==LamLcOutM(kkmuv)); xlc=xLcOutM{kkmuv}; ylc=yLcOutM{kkmuv}; hold on plot(xlc,ylc,'color',cmap(Lamidx,:),'linewidth',2.5); end axis equal tight % Add a second colorbar encoding the different \lambda values ax1 = gca; ax1_pos = ax1.Position; % position of first axes ax2 = axes('Position',ax1_pos,... 'XAxisLocation','bottom',... 'YAxisLocation','left',... 'Color','none'); hhF2 = colorbar(ax2,'eastOutside'); hhF2.FontSize = AxthicksFnt; set(get(hhF2,'xlabel'),'string','$$\lambda$$','Interpreter','latex','FontWeight','normal'); colormap(ax2,'jet') hhF2.Ticks=linspace(0,1,3); hhF2.XTickLabel={'0.9';'1';'1.1'}; set(ax2,'xtick',[]) set(ax2,'ytick',[]) set(ax2, 'visible', 'off') ; end end
github
haller-group/Closed-Null-Geodesics-2D-master
Phi_prime.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/Phi_prime.m
2,243
utf_8
3c5f187b58b0314eee6b9906f4ae3a7e
%% References: %[1] Mattia Serra and George Haller, "Efficient Computation of Null-Geodesic with % Applications to Coherent Vortex Detection", sumbitted, (2016). %% % [phiPrGr,C22mC11Gr,C12Gr]=Phi_prime(C11,C11x1,C11x2,C12,C12x1,C12x2,C22,C22x1,C22x2,x1_g,x2_g) % Input arguments: % Cij : ij entries of the C strain tensor % Cijx1 : x1-derivatice of the Cij entry % Cijx2 : x2-derivatice of the Cij entry % x1_g : x1 component of the spatial grid % x2_g : x2 component of the spatial grid % Output argument: % C22mC11Gr: gridded interpolant object for C22(x,y)-C11(x,y) % C12Gr : gridded interpolant object for C12(x,y) % phiPrGr : gridded interpolant object for \phi'(x,\phi) %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function [phiPrGr,C22mC11Gr,C12Gr]=Phi_prime(C11,C11x1,C11x2,C12,C12x1,C12x2,C22,C22x1,C22x2,x1_g,x2_g) %Define the \phi component of the spatial grid phi_g = linspace(0,2*pi,180); % Constract 3D arrays to build the gridded interpolant for \phi' C113df = repmat(C11,1,1,numel(phi_g)); C123df = repmat(C12,1,1,numel(phi_g)); C223df = repmat(C22,1,1,numel(phi_g)); C11x3d = repmat(C11x1,1,1,numel(phi_g)); C11y3d = repmat(C11x2,1,1,numel(phi_g)); C12x3d = repmat(C12x1,1,1,numel(phi_g)); C12y3d = repmat(C12x2,1,1,numel(phi_g)); C22x3d = repmat(C22x1,1,1,numel(phi_g)); C22y3d = repmat(C22x2,1,1,numel(phi_g)); [~,~,Z3d]=meshgrid(x1_g,x2_g,phi_g); % phi' (cf. eq. (38) of [1]) phiPr = -((C11x3d.*cos(Z3d)+C11y3d.*sin(Z3d)).*cos(Z3d).^2+(C12x3d.*cos(Z3d)+C12y3d.*sin(Z3d)).*sin(2*Z3d)+(C22x3d.*cos(Z3d)+C22y3d.*sin(Z3d)).*sin(Z3d).^2)./(sin(2*Z3d).*(C223df-C113df)+2*cos(2*Z3d).*C123df); phiPrGr = griddedInterpolant ({x1_g,x2_g,phi_g},permute(phiPr,[2 1 3]),'linear'); % Compute the (x)-dependent functions needed to define the domain of % existence V (cf. eq. (37) of [1]) of the reduced 3D null-geodesic flow (cf. eq. (38) of [1]). C22mC11Gr = griddedInterpolant ({x1_g,x2_g},permute(C22-C11,[2 1]),'linear'); C12Gr = griddedInterpolant ({x1_g,x2_g},permute(C12,[2 1]),'linear'); end
github
haller-group/Closed-Null-Geodesics-2D-master
FindOutermost.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/FindOutermost.m
2,834
utf_8
803304c13610eb9655ad4a5d39d10c44
%% References: %[1] Mattia Serra and George Haller, "Efficient Computation of Null-Geodesic with % Applications to Coherent Vortex Detection", sumbitted, (2016). %% % function [xLcOutM,yLcOutM,LamLcOutM]=FindOutermost(xPsol,yPsol,lamV,sVec); % Input arguments: % x1Psol : x1-component of closed null-geodesics % x2Psol : x2-component of closed null-geodesics % lamV : see steps 0-1 % sVec : see step 3 % Output arguments: % xLcOutM : x1-component of the outermost closed null-geodesics % yLcOutM : x2-component of the outermost closed null-geodesics % LamLcOutM : \lambda values corresponding to the outermost closed null-geodesics %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function [xLcOutM,yLcOutM,LamLcOutM]=FindOutermost(xPsol,yPsol,lamV,sVec) NMaxPts=length(sVec); xlcEx=[];ylcEx=[];lamfin=[];xcPos=[];ycPos=[];AreaLc=[]; for kkmuv=1:1:length(lamV) %save all the final curves in a cell xxapp=xPsol{kkmuv}; yyapp=yPsol{kkmuv}; if ~isempty(xxapp) for kkc=1:size(xxapp,2) xlc=xxapp(~isnan(xxapp(:,kkc)),kkc); ylc=yyapp(~isnan(yyapp(:,kkc)),kkc); %close the curve xlc(end)=xlc(1); ylc(end)=ylc(1); %compute the area Alc = polyarea(xlc,ylc); xlcEx=[xlcEx,[xlc(:);nan(NMaxPts-length(xlc),1)]]; ylcEx=[ylcEx,[ylc(:);nan(NMaxPts-length(xlc),1)]]; xCentLc=mean(xlc);yCentLc=mean(ylc); xcPos=[xcPos,xCentLc];ycPos=[ycPos,yCentLc]; AreaLc=[AreaLc,Alc]; lamfin=[lamfin,lamV(kkmuv)]; end end end % Sort the Lc in decreasing Area [~,ind]=sort(AreaLc,'descend'); AreaLc=AreaLc(ind); xcPos=xcPos(ind);ycPos=ycPos(ind); xlcEx=xlcEx(:,ind);ylcEx=ylcEx(:,ind);lamfin=lamfin(ind); % Extract the outermost toDel=[]; MatCheck=nan(size(xlcEx,2),size(xlcEx,2)); for kkmuv=1:1:size(xlcEx,2) xxapp=xlcEx(~isnan(xlcEx(:,kkmuv)),kkmuv); yyapp=ylcEx(~isnan(ylcEx(:,kkmuv)),kkmuv); in=inpolygon(xcPos,ycPos,xxapp,yyapp); MatCheck(kkmuv,:)=in; end for kkmuv=1:1:size(MatCheck,2) vettIdx=kkmuv+1:length(AreaLc); VettMat=MatCheck(kkmuv,kkmuv+1:size(MatCheck,2)); ToDelvett=vettIdx(VettMat==1); toDel=[toDel,ToDelvett]; end toDel=unique(toDel); xlcEx(:,toDel)=[]; ylcEx(:,toDel)=[]; lamfin(toDel)=[]; % Store the outermost closed null-geodesic xLcOutM=cell(1,size(xlcEx,2)); yLcOutM=cell(1,size(xlcEx,2)); LamLcOutM=nan(1,size(xlcEx,2)); for kkpl=1:size(xlcEx,2) LamLcOutM(kkpl)=lamfin(kkpl); xLcOutM{kkpl}=xlcEx(~isnan(xlcEx(:,kkpl)),kkpl); yLcOutM{kkpl}=ylcEx(~isnan(xlcEx(:,kkpl)),kkpl); end end
github
haller-group/Closed-Null-Geodesics-2D-master
FindClosedNullGeod.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/FindClosedNullGeod.m
3,053
utf_8
e648b671dcb8d9222859dbc53f0cb579
%% References: %[1] Mattia Serra and George Haller, "Efficient Computation of Null-Geodesic with % Applications to Coherent Vortex Detection", sumbitted, (2016). %% % function [x1Psol,x2Psol]=FindClosedNullGeod(C22mC11Gr,C12Gr,phiPrGr,x1_g,x2_g,lamV,sVec,options); % Input arguments: % C22mC11Gr, C12Gr, phiPrGr : see step 2 % x1_g, x2_g, lamV : see steps 0-1 % sVec, options : see step 3 % NCores : Number of cores for Parallel computing % Output arguments: % x1Psol : x1-component of closed null-geodesics % x2Psol : x2-component of closed null-geodesics %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function [x1Psol,x2Psol]=FindClosedNullGeod(C22mC11Gr,C12Gr,phiPrGr,x0lam,y0lam,phi0lam,x1_g,x2_g,lamV,sVec,options,NCores); % Initialize the variables containing the periodic solutions of the % initial value problem x1Psol = cell(1,length(lamV)); x2Psol = x1Psol; phiPsol = x1Psol; % Define the limits of the (x-y) domain to stop particles at the % boundary x1_glim = [min(x1_g),max(x1_g)]; x2_glim = [min(x2_g),max(x2_g)]; tic % Compute closed orbits of the Initial Value Problem (cf. eqs. (38-39) of [1]) for kklam = 1:1:length(lamV) kklam % Extract the r0_lam for the current value of \lambda x0 = x0lam{kklam}; y0 = y0lam{kklam}; phi0 = phi0lam{kklam}; lam=lamV(kklam); %% Opening MATLAB Pool %% Np=size(x0,1); cpu_num = min(NCores,Np); id = ceil( linspace(0,Np,cpu_num+1) ); poolobj = gcp('nocreate'); % If no pool, do not create new one. if isempty(poolobj) % if parpool is not open parpool('local',cpu_num) elseif (~isempty(poolobj)) && (poolobj.NumWorkers~=cpu_num) % if parpool is not consistent with cpu_num delete(gcp) parpool('local',cpu_num) end %% Integrate the ODE (38) in [1] tic spmd Range = id(labindex)+1:id(labindex+1); Z0loc = [x0(Range);y0(Range);phi0(Range)]; [~,xxfTot,yyfTot,zzfTot] = Advect_r(phiPrGr,C22mC11Gr,C12Gr,x1_glim,x2_glim,sVec,Z0loc,options); end toc % Put the trajectories of ODE (38) in matrix form X_Vf = cat(2,xxfTot{:}); Y_Vf = cat(2,yyfTot{:}); Z_Vf = cat(2,zzfTot{:}); %Warning in case of dimensionality mismatch if size(X_Vf,2)~=length(x0) disp('smpd dim. mismatch') end % Find periodic solutions [X1lco,X2lco,philco] = PeriodicSolutions(X_Vf,Y_Vf,Z_Vf); % Final curves in a cell x1Psol{kklam} = X1lco; x2Psol{kklam} = X2lco; phiPsol{kklam} = philco; end end
github
haller-group/Closed-Null-Geodesics-2D-master
Advect_r.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/Advect_r.m
2,455
utf_8
978d0c7efae18777e437ca0a4f95e6a9
%% References: %[1] Mattia Serra and George Haller, "Efficient Computation of Null-Geodesic with % Applications to Coherent Vortex Detection", sumbitted, (2016). %% % function [~,xxx,yyy,zzz]=Advect_r(phiPrGr,C22mC11Gr,C12Gr,x_glim,y_glim,sVec,Z0,options) % Input arguments: % C22mC11Gr, C12Gr, phiPrGr : see step 2 % x1_glim, x2_glim, : domain limits to stop particles if they % reach the boundaries % sVec, options : see step 3 % Z0 : Initial conditions % Output arguments: % xxx : x1-component of trajectories of the ODE (38) in [1] % yyy : x2-component of trajectories of the ODE (38) in [1] % zzz : \phi-component of trajectories of the ODE (38) in [1] %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function [Time,xxx,yyy,zzz] = Advect_r(phiPrGr,C22mC11Gr,C12Gr,x1_glim,x2_glim,sVec,Z0,options) % Shared variables x1m = x1_glim(1); x1M = x1_glim(2); x2m = x2_glim(1); x2M = x2_glim(2); Np = numel(Z0)/3; % Ode solver [Time,XXXpartcl] = ode45(@(t,zVec)r_prime(zVec),sVec,Z0,options); %% Function to evaluate r'(s) (cf. ODE (38) in [1]) function V_intrp = r_prime(zVecs) XXxx=zVecs(1:Np); YYyy=zVecs(1+Np:2*Np); ZZzz=zVecs(1+2*Np:3*Np); % Freeze particles at the boundaries of the doamin or when the ODE % (38) is not defined Bll=1+0*XXxx; Bll(XXxx>x1M)=0;Bll(XXxx<x1m)=0; Bll(YYyy>x2M)=0;Bll(YYyy<x2m)=0; % Freeze particles at the boundaries of the domain of definition V (cf eq. (37) of [1]) of % the ODE (38) of [1]. % Domain of existence DoE=2*C12Gr(XXxx,YYyy).*cos(2*ZZzz)+sin(2*ZZzz).*C22mC11Gr(XXxx,YYyy); Bll(abs(DoE)<1e-2)=0; % Evaluate r'(s) utemp_scp=cos(ZZzz); vtemp_scp=sin(ZZzz); wtemp_scp=phiPrGr(XXxx,YYyy,ZZzz); Norma=sqrt(utemp_scp.^2+vtemp_scp.^2+wtemp_scp.^2); V_intrp=[utemp_scp./Norma.*Bll;vtemp_scp./Norma.*Bll;wtemp_scp./Norma.*Bll]; end xxx=XXXpartcl(:,1:Np); yyy=XXXpartcl(:,1+Np:2*Np); zzz=XXXpartcl(:,1+2*Np:3*Np); end
github
haller-group/Closed-Null-Geodesics-2D-master
r0_lam.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/r0_lam.m
2,234
utf_8
1be846cd61314ab3dd3afb6f7a3c7d25
%% References: %[1] Mattia Serra and George Haller, "Efficient Computation of Null-Geodesic with % Applications to Coherent Vortex Detection", sumbitted, (2016). %% % function [x0lam,y0lam,phi0lam]=r0_lam(lamV,C11,C12,C22,x_g,y_g) % Input arguments: % lamV : Desired set of \lambda values % Cij : ij entries of the C strain tensor % x_g : x component of the spatial grid % y_g : y component of the spatial grid % Output arguments: % x0lam: x-coordinates of r0_lam % y0lam: y-coordinates of r0_lam % phi0lam: phi-coordinates of r0_lam %Note: This function returns the intial condition r0_lam for any value of %phi0 \in [0,2\pi). Since this choice is arbitrary, in [1] %we picked phi0=0, leading to the simplified formula (39) in [1]. %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function [x0lam,y0lam,phi0lam]=r0_lam(lamV,C11,C12,C22,x_g,y_g) %Define the initial \phi value: \phi_0 (cf. Fig. 2 of [1]) phi0 = 0; % Initialize the output variables x0lam = cell(1,length(lamV)); y0lam = x0lam; phi0lam = x0lam; % Compute the initial conditions r0_\lambda for different values of \lambda for kkmu = 1:length(lamV) lam = (lamV(kkmu)); ZeroSet = (cos(phi0))^2*C11+sin(2*phi0)*C12+(sin(phi0))^2*C22-lam^2; %Discard the points where out of the domain of existence V (cf. eq. (37) of [1]) DoE = 2*C12.*cos(2*phi0)+sin(2*phi0).*(C22-C11); ZeroSet(abs(DoE)<1e-2) = nan; % Extract the x_0(\lambda,\phi_0) (cf. Fig. 2b or eq.(39) of [1]) CC = contourc(x_g,y_g,ZeroSet,[0,0]); ss = getcontourlines(CC); XXvTzero = []; YYvTzero = []; for kkk=1:size(ss,2) XXvTzero = [XXvTzero;(ss(kkk).x)']; YYvTzero = [YYvTzero;(ss(kkk).y)']; end ZZvTzero = phi0+0*XXvTzero; % Cell variables containing the x,y,\phi coordinates of \lambda-dependent zero level set x0lam{kkmu} = XXvTzero; y0lam{kkmu} = YYvTzero; phi0lam{kkmu} = ZZvTzero; end end
github
haller-group/Closed-Null-Geodesics-2D-master
PeriodicSolutions.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/PeriodicSolutions.m
5,724
utf_8
89699760a218aea7448fc5c4c93964b2
%% References: %[1] Mattia Serra and George Haller, "Efficient Computation of Null-Geodesic with % Applications to Coherent Vortex Detection", sumbitted, (2016). %% % function [X1lco,X2lco,philco]=PeriodicSolutions(X_Vf,Y_Vf,Z_Vf) % Input arguments: % X_Vf : x1-component of the trajectories of the ODE (38) in [1] % Y_Vf : x2-component of the trajectories of the ODE (38) in [1] % Z_Vf : \phi-component of the trajectories of the ODE (38) in [1] % Output arguments: % X1lco : x1-component of periodic solutions of ODE (38) in [1] % X2lco : x2-component of periodic solutions of ODE (38) in [1] % philco : \phi-component of periodic solutions of ODE (38) in [1] %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function [X1lco,X2lco,philco] = PeriodicSolutions(X_Vf,Y_Vf,Z_Vf) X1lco=[];X2lco=[];philco=[]; % Topological condition: discard the traject that have no Z values close to abs(2*pi) MaxPerCol=max(abs(Z_Vf)); MinZVal=0.95*2*pi; X_Vf=X_Vf(:,MaxPerCol>MinZVal); Y_Vf=Y_Vf(:,MaxPerCol>MinZVal); Z_Vf=Z_Vf(:,MaxPerCol>MinZVal); % C^1 distance distance2d02pi=sqrt((repmat(X_Vf(1,:),size(X_Vf,1),1)-X_Vf).^2+(repmat(Y_Vf(1,:),size(Y_Vf,1),1)-Y_Vf).^2+(abs(repmat(Z_Vf(1,:),size(Z_Vf,1),1)-Z_Vf)-2*pi).^2); % Avoid to get the first points ReturnDist=2*1e-2; % Avoid to scan all the set of initial conditions to find closed null-geodesics distance2d02pi(abs(Z_Vf)<0.8*2*pi)=nan; [valret,indrw]=min(distance2d02pi); indrw(valret>ReturnDist)=[]; X_Vf(:,valret>ReturnDist)=[]; Y_Vf(:,valret>ReturnDist)=[]; Z_Vf(:,valret>ReturnDist)=[]; valret(valret>ReturnDist)=[]; % Set to nan the points following the closest one for kkss=1:length(indrw) X_Vf(indrw(kkss)+1:end,kkss)=nan; Y_Vf(indrw(kkss)+1:end,kkss)=nan; Z_Vf(indrw(kkss)+1:end,kkss)=nan; end [~,ind]=sort(valret,'ascend'); indrw=indrw(ind); xIn=X_Vf(1,:); yIn=Y_Vf(1,:); MatrixFin=[]; % Filter the ones which do not have a change of spiraling InDist=0.1; % Avoid to scan all the set of initial conditions to find the 2 closest initial conditions to the current initial point contained in the set for kkh=1:length(ind) indFull=[]; ind12=[];sign12=0; %analyze each trajectory x00=X_Vf(1,ind(kkh));y00=Y_Vf(1,ind(kkh)); %find the 2 closest initial conditions on the initial set AlNorDir=mod(atan2((Y_Vf(2,ind(kkh))-y00),(X_Vf(2,ind(kkh))-x00))+pi/2,2*pi); distan=sqrt((xIn-x00).^2+(yIn-y00).^2); [vald,indd]=sort(distan,'ascend'); indd(vald>InDist)=[]; vald(vald>InDist)=[]; indd(vald==0)=[]; vald(vald==0)=[]; if ~isempty(indd) xn=xIn(indd(1:end));yn=yIn(indd(1:end)); AlneighDir=mod(atan2((yn-y00),(xn-x00)),2*pi); dotpr=[cos(AlNorDir) sin(AlNorDir)]*[cos(AlneighDir);sin(AlneighDir)]; Boolsd=0*AlneighDir-1; Boolsd(AlneighDir>AlNorDir+pi/2)=1; ind12=[ind12;indd(1)]; sign12=(Boolsd(1)); sign12Bool=sign12*Boolsd; [~,inddd]=find(sign12Bool<0); if ~isempty(inddd) ind12=[ind12;indd(inddd(1))]; end if length(ind12)==2 indFull=[ind12(1);ind(kkh);ind12(2)]; % Check the change of spiraling Matr=[]; spiral=[]; dist=[]; for kkcs=1:length(indFull) indcol=indFull(kkcs); InN1=length(X_Vf(~isnan(X_Vf(:,indcol)),indcol)); AlNorDircon=mod(atan2((Y_Vf(2,indcol)-Y_Vf(1,indcol)),(X_Vf(2,indcol)-X_Vf(1,indcol)))+pi/2,2*pi); AlneighDircon=mod(atan2((Y_Vf(InN1,indcol)-Y_Vf(1,indcol)),(X_Vf(InN1,indcol)-X_Vf(1,indcol))),2*pi); AlneighAbsDist=sqrt((Y_Vf(InN1,indcol)-Y_Vf(1,indcol)).^2+(X_Vf(InN1,indcol)-X_Vf(1,indcol)).^2); spiral=[spiral;-sign([cos(AlNorDircon) sin(AlNorDircon)]*[cos(AlneighDircon);sin(AlneighDircon)])]; % Distance projected along the local normal locDistVec=AlneighAbsDist*[cos(AlneighDircon),sin(AlneighDircon)]; ProjVectDist=locDistVec*[cos(AlNorDircon);sin(AlNorDircon)]; dist=[dist;abs(ProjVectDist)]; end Matr=[indFull,spiral,dist]; % If there is a change of spiraling, take the selected point with % min return distance if Matr(1,2)*Matr(2,2)<0 | Matr(3,2)*Matr(2,2)<0 MatrixFin=[MatrixFin;Matr(2,:)]; end end end end if ~isempty(MatrixFin) MatrixFinal=MatrixFin; [~,indddd]=sort(MatrixFinal(:,1),'ascend'); MatrixFinal=MatrixFinal(indddd,:); Idxtodel=[]; for kk=1:size(MatrixFinal,1)-1 if abs(MatrixFinal(kk+1,1)-MatrixFinal(kk,1))==1 %if they are consecutive IC discard the one with max return distance (this avoids to have the same null-geodesic twice) [~,idistc]=max(MatrixFinal(kk:kk+1,end)); if idistc==2 Idxtodel=[Idxtodel;kk+1]; else Idxtodel=[Idxtodel;kk]; end end end MatrixFinal(Idxtodel,:)=[]; indFFin=MatrixFinal(:,1); X1lco=X_Vf(:,indFFin); X2lco=Y_Vf(:,indFFin); philco=Z_Vf(:,indFFin); % Final closed null-geodesics for kk=1:size(X1lco,2)-1 x1=X1lco(~isnan(X1lco(:,kk)),kk); x2=X2lco(~isnan(X2lco(:,kk)),kk); x1(end)=x1(1);x2(end)=x2(1); X1lco(~isnan(X1lco(:,kk)),kk)=x1; X2lco(~isnan(X2lco(:,kk)),kk)=x2; end end end
github
haller-group/Closed-Null-Geodesics-2D-master
PlotAllClosedNullGeodesics.m
.m
Closed-Null-Geodesics-2D-master/Subfunctions/PlotAllClosedNullGeodesics.m
2,577
utf_8
265d9d1e1e7298b68083091ccc61ebb6
% function PlotAllClosedNullGeodesics(x1Psol,x2Psol,x1_g,x2_g,lamV,lam2) % Input arguments: % lamV : Desired set of \lambda values % phi0 : initial \phi value (cf. Fig. 2 of [1]) % CGij : ij entries of the CG strain tensor % x1_g : x1 component of the spatial grid % x2_g : x2 component of the spatial grid %-------------------------------------------------------------------------- % Author: Mattia Serra [email protected] % http://www.zfm.ethz.ch/~serra/ %-------------------------------------------------------------------------- function PlotAllClosedNullGeodesics(x1Psol,x2Psol,x1_g,x2_g,lamV,lam2) % Colormap encoding different \lambda values cmap = jet(length(lamV)); % Plot properties AxthicksFnt = 15; fontsizeaxlab = 15; if ~isempty(x1Psol) % If there are closed null-geodesics % Initialize the figure with the FTLE plot figure('units','normalized','outerposition',[0 0 .5 .5]); imagesc(x1_g,x2_g,log(lam2)/30/2);shading interp set(gca,'FontSize',AxthicksFnt,'fontWeight','normal') hold on set(gca,'YDir','normal') set(gcf,'color','w'); axis equal xlabel('$$Lon [^{\circ}]$$','Interpreter','latex','FontWeight','bold','FontSize',fontsizeaxlab); ylabel('$$Lat [^{\circ}]$$','Interpreter','latex','FontWeight','bold','FontSize',fontsizeaxlab); axis equal tight colormap(gca,'gray') hhF=colorbar(gca); hhF.Location='westOutside'; hhF.FontSize=fontsizeaxlab; set(get(hhF,'xlabel'),'string','$$FTLE$$','Interpreter','latex','FontWeight','normal'); for kkmuv=1:1:length(lamV) xxapp=x1Psol{kkmuv}; yyapp=x2Psol{kkmuv}; if ~isempty(xxapp) for kkc=1:size(xxapp,2) xlc=xxapp(~isnan(xxapp(:,kkc)),kkc); ylc=yyapp(~isnan(yyapp(:,kkc)),kkc); hold on plot(xlc,ylc,'color',cmap(kkmuv,:),'linewidth',2.5) end end end axis equal tight %add a second colorbar for the \lambda values ax1=gca; ax1_pos = ax1.Position; ax2 = axes('Position',ax1_pos,... 'XAxisLocation','bottom',... 'YAxisLocation','left',... 'Color','none'); hhF2 = colorbar(ax2,'eastOutside') hhF2.FontSize=AxthicksFnt; set(get(hhF2,'xlabel'),'string','$$\lambda$$','Interpreter','latex','FontWeight','normal'); colormap(ax2,'jet') hhF2.Ticks=linspace(0,1,3); hhF2.XTickLabel={'0.9';'1';'1.1'}; set(ax2,'xtick',[]) set(ax2,'ytick',[]) set(ax2, 'visible', 'off') ; end end
github
PrincetonUniversity/3D3A-SABRE-Toolkit-master
SABRE_SphericalHarmonic.m
.m
3D3A-SABRE-Toolkit-master/SABRE_SphericalHarmonic.m
3,326
utf_8
8364057f4d5325bc0be08b1baff9b0ca
function Y = SABRE_SphericalHarmonic(L, R) %SABRE_SphericalHarmonic Real-valued spherical harmonic function for ambiX. % Y = SABRE_SphericalHarmonic(L,R) computes the real-valued, SN3D % normalized spherical harmonics, up to order L and for positions R, % used in the ambiX plugins. The ambiX spherical harmonic convention % is described by Nachbar et al. [1] and Kronlachner [2]. % % Note: % L must be a scalar. % R may be a P-by-3 matrix of directions, where each row is a % Cartesian vector. % Y will be a (L + 1)^2-by-P matrix. % ============================================================================== % This file is part of the 3D3A SABRE Toolkit. % % Joseph G. Tylka <[email protected]> % 3D Audio and Applied Acoustics (3D3A) Laboratory % Princeton University, Princeton, New Jersey 08544, USA % % MIT License % % Copyright (c) 2017 Princeton University % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. % ============================================================================== % Needs at least 2 input arguments if nargin < 2 error('Not enough input arguments.'); end % Compute spherical harmonic matrix Y = zeros((L + 1)^2, size(R,1)); for l = 0:L for m = -l:l acn = l*(l + 1) + m; Y(acn + 1,:) = ambiXsphericalHarmonic(l, m, R); end end end function Y = ambiXsphericalHarmonic(l,m,r) % Needs at least 3 input arguments if nargin < 3 error('Not enough input arguments.'); end if (l >= 0) && (abs(m) <= l) if isvector(r) [AZIM,ELEV,~] = cart2sph(r(1),r(2),r(3)); else [AZIM,ELEV,~] = cart2sph(r(:,1),r(:,2),r(:,3)); end % Compute normalization term Nlm = ambiXnormalization(l,abs(m)); % Compute elevation term Pl = legendre(l, sin(ELEV)); Plm = Pl(abs(m) + 1,:).'; % Compute azimuth term if m >= 0 Tm = cos(m * AZIM); else % m < 0 Tm = sin(abs(m) * AZIM); end Y = Nlm*Plm.*Tm; else warning('Invalid order and degree.'); Y = 0; end end function Nlm = ambiXnormalization(l,m) Nlm = ((-1)^m)*sqrt((2-(~m))/(4*pi)).*sqrt(factorial(l-m)./factorial(l+m)); % Includes Condon-Shortley phase ((-1)^m) to cancel it in the Legendre term. end
github
PrincetonUniversity/3D3A-SABRE-Toolkit-master
SABRE_InterpolateHRTFs.m
.m
3D3A-SABRE-Toolkit-master/SABRE_InterpolateHRTFs.m
7,851
utf_8
21888ca5a9f7b7c50fb72a87ae244f1e
function [hrirL, hrirR, desiredGrid] = SABRE_InterpolateHRTFs(hrirDataL, hrirDataR, measuredGrid, varargin) %SABRE_InterpolateHRTFs Interpolate measured HRTFs to a desired grid. % [XL, XR, RD] = SABRE_InterpolateHRTFs(HL, HR, RM, RD) returns HRIRs XL % and XR for the desired positions RD, given input HRIRs HL and HR % that are measured at positions RM. The returned HRIRs are the % 'nearest neighbors,' computed by finding the nearest point on the % measured grid to each point on the desired grid and returning the % corresponding measured HRIRs. % % [XL, XR, RD] = SABRE_InterpolateHRTFs(HL, HR, RM, RD, METHOD) uses one % of the following interpolation methods: % 'nearest' - Nearest neighbor interpolation (default) % 'natural' - Natural neighbor interpolation % 'linear' - Linear interpolation % 'sh' - Spherical-harmonic interpolation % % [XL, XR, RD] = SABRE_InterpolateHRTFs(HL, HR, RM, RD, METHOD, DOMAIN) % performs interpolation in either of the following domains: % 'time' - Averages time-aligned impulse responses (default) % 'frequency' - Averages magnitude spectra in dB and computes % minimum-phase impulse responses % % [XL, XR, RD] = SABRE_InterpolateHRTFs(HL, HR, RM, RD, METHOD, DOMAIN, THRESHOLD) % limits interpolation to only those desired grid positions that are % at least THRESHOLD degrees away from the nearest measurement % position. Within the THRESHOLD, nearest-neighbor interpolation is % used. % % [XL, XR, RD] = SABRE_InterpolateHRTFs(HL, HR, RM, CONFIG) interpolates % the measured HRIRs using specified CONFIG settings. % % See also SABRE_LoadHRTFs, SABRE_RemoveHRTFDelays, SABRE_AddHRTFDelays. % ============================================================================== % This file is part of the 3D3A SABRE Toolkit. % % Joseph G. Tylka <[email protected]> % 3D Audio and Applied Acoustics (3D3A) Laboratory % Princeton University, Princeton, New Jersey 08544, USA % % MIT License % % Copyright (c) 2017 Princeton University % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. % ============================================================================== narginchk(4,7); if nargin == 4 && isstruct(varargin{1}) config = varargin{1}; else if nargin >= 4 config.interpolation_grid = varargin{1}; end if nargin >= 5 config.interpolation_method = varargin{2}; end if nargin >= 6 config.interpolation_domain = varargin{3}; end if nargin == 7 config.interpolation_threshold = varargin{4}; end end if ~isfield(config,'interpolation_method') config.interpolation_method = 'nearest'; end if ~isfield(config,'interpolation_domain') config.interpolation_domain = 'time'; end if ~isfield(config,'interpolation_threshold') config.interpolation_threshold = 0; end desiredGrid = config.interpolation_grid; hrirLen = size(hrirDataL,1); numDirs = size(desiredGrid,1); numMeas = size(measuredGrid,1); hrirL = zeros(hrirLen, numDirs); hrirR = zeros(hrirLen, numDirs); % Normalize vectors to be on unit sphere desiredGrid = desiredGrid ./(sqrt(dot(desiredGrid ,desiredGrid ,2))*ones(1,size(desiredGrid ,2))); measuredGrid = measuredGrid./(sqrt(dot(measuredGrid,measuredGrid,2))*ones(1,size(measuredGrid,2))); switch lower(config.interpolation_method) case 'nearest' % Find nearest measured HRTFs for ii = 1:numDirs distVec = sqrt(sum((measuredGrid - ones(numMeas,1)*desiredGrid(ii,:)).^2,2)); indx = find(distVec == min(distVec),1,'first'); hrirL(:,ii) = hrirDataL(:,indx); hrirR(:,ii) = hrirDataR(:,indx); desiredGrid(ii,:) = measuredGrid(indx,:); end case {'natural','linear','sh'} % Interpolate HRTFs w = interpWeights(measuredGrid, desiredGrid, lower(config.interpolation_method)); % Apply interpolation threshold interpNeeded = ~zeros(1,numDirs); % for logical indexing of which positions need interpolation for ii = 1:numDirs distVec = sqrt(sum((measuredGrid - ones(numMeas,1)*desiredGrid(ii,:)).^2,2)); indx = find(distVec == min(distVec),1,'first'); angDist = acosd(dot(measuredGrid(indx,:),desiredGrid(ii,:),2)); if angDist < config.interpolation_threshold interpNeeded(ii) = false; % prevent overwriting below % Copy measurements directly hrirL(:,ii) = hrirDataL(:,indx); hrirR(:,ii) = hrirDataR(:,indx); desiredGrid(ii,:) = measuredGrid(indx,:); end end [irL, irR, dL, dR, d0] = SABRE_RemoveHRTFDelays(hrirDataL, hrirDataR); dLi = dL*w(:,interpNeeded); dRi = dR*w(:,interpNeeded); switch lower(config.interpolation_domain) case 'time' irLi = irL*w(:,interpNeeded); irRi = irR*w(:,interpNeeded); case 'frequency' HdBL = mag2db(abs(fft(hrirDataL,hrirLen,1))); HdBR = mag2db(abs(fft(hrirDataR,hrirLen,1))); irLi = minimumPhase(ifft(db2mag(HdBL*w(:,interpNeeded)),hrirLen,1,'symmetric')); irRi = minimumPhase(ifft(db2mag(HdBR*w(:,interpNeeded)),hrirLen,1,'symmetric')); dLi = dLi + d0; dRi = dRi + d0; end [hrirL(:,interpNeeded), hrirR(:,interpNeeded)] = SABRE_AddHRTFDelays(irLi, irRi, dLi, dRi); % TODO: Add other interpolation methods here... end end function w = interpWeights(posIn,posOut,METHOD,OPTION) narginchk(2,4); if nargin < 3 METHOD = 'linear'; end if strcmpi(METHOD,'sh') if nargin < 4 || isempty(OPTION) maxOrder = 4; else maxOrder = OPTION; end YmatrixIn = SABRE_SphericalHarmonic(maxOrder, posIn); YmatrixOut = SABRE_SphericalHarmonic(maxOrder, posOut); w = YmatrixIn\YmatrixOut; % numPosIn-by-numPosOut else numPosIn = size(posIn,1); numPosOut = size(posOut,1); w = zeros(numPosIn,numPosOut); for jj = 1:numPosOut [y, p, ~] = cart2sph(posOut(jj,1),posOut(jj,2),posOut(jj,3)); Rz = [cos(y) -sin(y) 0; sin(y) cos(y) 0; 0 0 1]; Ry = [cos(p) 0 -sin(p); 0 1 0; sin(p) 0 cos(p)]; posInR = posIn*Rz*Ry; [posInS(:,1),posInS(:,2),~] = cart2sph(posInR(:,1),posInR(:,2),posInR(:,3)); % Get "impulse responses" of interpolation function for ii = 1:numPosIn v = zeros(numPosIn,1); v(ii) = 1; F = scatteredInterpolant(posInS,v,METHOD); w(ii,jj) = F([0 0]); end end end end
github
kohpangwei/data-poisoning-release-master
upperBoundTrue.m
.m
data-poisoning-release-master/matlab/upperBoundTrue.m
6,944
utf_8
212d5d2bb6860fc19366e570c83dd283
% G, Constraint are yalmip data for debugging function [G, Constraint, val, X_eps, probs_eps] = upperBoundTrue(X_train, y_train, theta, bias, probs, mus, epsilon, r_slab, r_sphere, randomize, solver) % we don't have a good way of splitting u pthe probabilities, so let's % just do it randomly if randomize probs_eps = gamrnd([probs(1) probs(1) probs(2) probs(2)], 1); probs_eps = epsilon * probs_eps / sum(probs_eps); else % this heuristic choice also works well probs_eps = epsilon * [probs(1) 0 probs(2) 0]; end % who are the relevant players? % x_a^+, x_b^+, x_a^-, x_b^- % mu^+, mu^-, theta Norms = [norm(mus(:,1),2); norm(mus(:,2),2); norm(theta,2)]; %Norms %D = eig(mus' * mus); %D M_m = [mus(:,1)/Norms(1) mus(:,2)/Norms(2) theta/Norms(3)]; G_m = M_m' * M_m; %E = eig(G_m); %E %G_o = sdpvar(4,4); %G_s = sdpvar(4,3); %G = [G_o G_s; G_s' G_m]; G = sdpvar(7,7); %Slack = 1e-5 * diag([1 1 1 1 1 1 1]); Constraint = [G >= 0; G(5:7,5:7) == G_m]; e_ap = [1;0;0;0;0;0;0]; % x_a^+; this one is a support vector e_bp = [0;1;0;0;0;0;0]; % x_b^+; this one is not a support vector e_am = [0;0;1;0;0;0;0]; % x_a^- e_bm = [0;0;0;1;0;0;0]; % x_b^- e_up = [0;0;0;0;Norms(1);0;0]; % mu^+ e_um = [0;0;0;0;0;Norms(2);0]; % mu^- e_th = [0;0;0;0;0;0;Norms(3)]; % theta mu_pp = (probs(1) * e_up + probs_eps(1) * e_ap + probs_eps(2) * e_bp) / (probs(1) + probs_eps(1) + probs_eps(2)); %mu_poisoned^+ mu_mp = (probs(2) * e_um + probs_eps(3) * e_am + probs_eps(4) * e_bm) / (probs(2) + probs_eps(3) + probs_eps(4)); %mu_poisoned^- % add inner product constraint Constraint = [Constraint; 1 - (e_ap' * G * e_th + bias) >= 0; % i.e., 1 - <x_a^+, theta> >= 0 %1 - (e_bp' * G * e_th + bias) <= 0; 1 + (e_am' * G * e_th + bias) >= 0]; %1 + (e_bm' * G * e_th + bias) <= 0]; % add sphere constraints Constraint = [Constraint; (e_ap - mu_pp)' * G * (e_ap - mu_pp) <= r_sphere(1)^2; % i.e., <x_a^+ - mu_poisoned^+, x_a^+ - mu_poisoned^+ > <= r_sphere^2 (e_bp - mu_pp)' * G * (e_bp - mu_pp) <= r_sphere(1)^2; (e_am - mu_mp)' * G * (e_am - mu_mp) <= r_sphere(2)^2; (e_bm - mu_mp)' * G * (e_bm - mu_mp) <= r_sphere(2)^2]; % add slab constraints dist_sq = norm(mus(:,1) - mus(:,2),2)^2; s1 = sdpvar; s2 = sdpvar; s3 = sdpvar; s4 = sdpvar; Constraint = [Constraint; s1 == ((e_ap - mu_pp)' * G * (mu_pp - mu_mp)); s2 == ((e_bp - mu_pp)' * G * (mu_pp - mu_mp)); s3 == ((e_am - mu_mp)' * G * (mu_pp - mu_mp)); s4 == ((e_bm - mu_mp)' * G * (mu_pp - mu_mp)); s1^2 <= (r_slab(1)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp); s2^2 <= (r_slab(1)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp); s3^2 <= (r_slab(2)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp); s4^2 <= (r_slab(2)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp)]; %((e_ap - mu_pp)' * G * (mu_pp - mu_mp))^2 <= (r_slab(1)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp); %((e_bp - mu_pp)' * G * (mu_pp - mu_mp))^2 <= (r_slab(1)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp); %((e_am - mu_mp)' * G * (mu_pp - mu_mp))^2 <= (r_slab(2)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp); %((e_bm - mu_mp)' * G * (mu_pp - mu_mp))^2 <= (r_slab(2)^2/dist_sq) * (mu_pp - mu_mp)' * G * (mu_pp - mu_mp)]; %-r_slab(1) <= (e_ap - mu_pp)' * G * (mu_pp - mu_mp) <= r_slab(1); % i.e., -r_slab <= <x_a^+ - mu_poisoned^+, mu_poisoned^+ - mu_poisoned^_ > <= r_slab %-r_slab(1) <= (e_bp - mu_pp)' * G * (mu_pp - mu_mp) <= r_slab(1); %-r_slab(2) <= (e_am - mu_mp)' * G * (mu_pp - mu_mp) <= r_slab(2); %-r_slab(2) <= (e_bm - mu_mp)' * G * (mu_pp - mu_mp) <= r_slab(2)]; Objective = probs_eps(1) * (1 - (e_ap' * G * e_th + bias)) + probs_eps(3) * (1 + (e_am' * G * e_th + bias)); % loss on the support vectors x_a^+ and x_a^- opts = sdpsettings('verbose', 0, 'showprogress', 0, 'solver', solver, 'cachesolvers', 1); optimize(Constraint, -Objective, opts); val = double(Objective); fprintf(1, 'value = %.4f \t (eps = [%.3f %.3f %.3f %.3f])\n', val, probs_eps(1), probs_eps(2), probs_eps(3), probs_eps(4)); %[~, L0] = nabla_Loss(X_train, y_train, theta); %fprintf(1, 'upper bound: %.4f (all) | %.4f (L0) | %.4f (val)\n', L0 + val, L0, val); G_d = double(G); %X_eps' * X_eps; errIn = norm(G_d(5:7,5:7) - G_m, 'inf'); if errIn > 1e-4 fprintf(1, 'errIn = %.5f, skipping...\n', errIn); X_eps = [mus(:,1) mus(:,1) mus(:,2) mus(:,2)]; G_feas = [X_eps M_m]' * [X_eps M_m]; assign(G, G_feas); check(Constraint); val = 1e3; return; end if nargout > 3 X_eps = extractVecs(double(G), G_m, M_m); %[mus theta]); G_approx = X_eps' * X_eps; % check constraints feas_sphere = [ (e_ap - mu_pp)' * G_approx * (e_ap - mu_pp) / r_sphere(1)^2; (e_bp - mu_pp)' * G_approx * (e_bp - mu_pp) / r_sphere(1)^2; (e_am - mu_mp)' * G_approx * (e_am - mu_mp) / r_sphere(2)^2; (e_bm - mu_mp)' * G_approx * (e_bm - mu_mp) / r_sphere(2)^2]; %feas_slab = [ abs((e_ap - mu_pp)' * G_approx * (mu_pp - mu_mp)) / r_slab(1); % abs((e_bp - mu_pp)' * G_approx * (mu_pp - mu_mp)) / r_slab(1); % abs((e_am - mu_mp)' * G_approx * (mu_pp - mu_mp)) / r_slab(2); % abs((e_bm - mu_mp)' * G_approx * (mu_pp - mu_mp)) / r_slab(2)]; feas_slab = [ ((e_ap - mu_pp)' * G_approx * (mu_pp - mu_mp))^2 / ((r_slab(1)^2/dist_sq) * (mu_pp - mu_mp)' * G_approx * (mu_pp - mu_mp)); ((e_bp - mu_pp)' * G_approx * (mu_pp - mu_mp))^2 / ((r_slab(1)^2/dist_sq) * (mu_pp - mu_mp)' * G_approx * (mu_pp - mu_mp)); ((e_am - mu_mp)' * G_approx * (mu_pp - mu_mp))^2 / ((r_slab(2)^2/dist_sq) * (mu_pp - mu_mp)' * G_approx * (mu_pp - mu_mp)); ((e_bm - mu_mp)' * G_approx * (mu_pp - mu_mp))^2 / ((r_slab(2)^2/dist_sq) * (mu_pp - mu_mp)' * G_approx * (mu_pp - mu_mp))]; fprintf(1, 'feasibility: %.3f %.3f %.3f %.3f (sphere) | %.3f %.3f %.3f %.3f (slab)\n', ... feas_sphere(1), feas_sphere(2), feas_sphere(3), feas_sphere(4), ... feas_slab(1), feas_slab(2), feas_slab(3), feas_slab(4)); X_eps = X_eps(:,1:4); end end
github
kohpangwei/data-poisoning-release-master
extractVecs.m
.m
data-poisoning-release-master/matlab/extractVecs.m
1,607
utf_8
6ed8c565810c85c34eda832eb00d180a
function V_full = extractVecs(G_full, G_partial, V_partial) % G_full is Graham matrix of inner products % G_partial is lower-right corner of G % V_partial is collection of vectors realizing G_partial n_full = size(G_full, 1); assert(n_full == size(G_full, 2)); n_partial = size(G_partial, 1); n_missing = n_full - n_partial; assert(n_partial == size(G_partial, 2)); assert(n_partial == size(V_partial, 2)); d = size(V_partial, 1); [Proj_half, ~] = svd_lr(V_partial, 1e-6); G_11 = G_full(1:n_missing,1:n_missing); G_12 = G_full(1:n_missing,n_missing+1:n_full); G_22 = G_full(n_missing+1:n_full,n_missing+1:n_full); [U_22, D_22] = eig_lr(G_22, 1e-6); Gp_12 = G_12 * U_22; Gp_22_pinv_sqrt = sqrt(inv(D_22)); Gp_schur_sqrt = Gp_12 * Gp_22_pinv_sqrt; Bp = Gp_schur_sqrt * Gp_22_pinv_sqrt'; AAt = (G_11 - (Gp_schur_sqrt * Gp_schur_sqrt')); [U_a, D_a] = eig(AAt); A = U_a * sqrt(max(D_a,0)); basis = randn(d,n_missing); basis = basis - Proj_half * (Proj_half' * basis); [basis, ~] = qr(basis, 0); V_missing = basis * A' + V_partial * U_22 * Bp'; V_full = [V_missing V_partial]; err = norm(G_full - (V_full'*V_full), 'inf'); fprintf(1, 'err: %.4f\n', err); end function [U,D] = svd_lr(A, tol) [U,D,~] = svd(A, 'econ'); active = diag(D) > tol*max(D(:)); U = U(:,active); D = D(active,active); end function [U,D] = eig_lr(A, tol) [U,D] = eig((A+A')/2); active = diag(D)>tol*max(D(:)); U = U(:, active); D = D(active,active); end
github
aharley/segaware-master
classification_demo.m
.m
segaware-master/caffe/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
aharley/segaware-master
MyVOCevalseg.m
.m
segaware-master/caffe/matlab/my_script/MyVOCevalseg.m
4,625
utf_8
128c24319d520c2576168d1cf17e068f
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
aharley/segaware-master
MyVOCevalsegBoundary.m
.m
segaware-master/caffe/matlab/my_script/MyVOCevalsegBoundary.m
4,415
utf_8
1b648714e61bafba7c08a8ce5824b105
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w) % get structural element st_w = 2*w + 1; se = strel('square', st_w); % image test set fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset); fid = fopen(fn, 'r'); gtids = textscan(fid, '%s'); gtids = gtids{1}; fclose(fid); %[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end % dilate gt binary_gt = gtim == 255; dilate_gt = imdilate(binary_gt, se); target_gt = dilate_gt & (gtim~=255); %pixel locations to include in computation locs = target_gt; %locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; else class_count = class_count + 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end accuracies = accuracies(1:end); avacc = mean(accuracies); fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
aharley/segaware-master
MyVOCevalseg.m
.m
segaware-master/scripts/segaware/matlab/eval/MyVOCevalseg.m
4,821
utf_8
e2ba8ed0ce8588906a6c63e3a76eb9b2
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); %fprintf([VOCopts.seg.clsimgpath '\n'],imname) % results file %fprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); %fprintf('\n'); resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); %fprintf([VOCopts.seg.clsrespath '\n'],id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
Unisens/unisensMatlabTools-master
unisensBin2Csv.m
.m
unisensMatlabTools-master/unisensBin2Csv.m
5,391
utf_8
02ce00d793b19e479aaa3464084aa4f4
function unisensBin2Csv(path, keepSensorScaling, new_path) %UNISENSBIN2CSV convert unisens dataset with bin entries to dataset with csv entries % Converts all unisens signal entries from binary format (*.bin) to csv format (*.csv) % Copyright 2017 movisens GmbH addUnisensJar(); if nargin==0 || nargin>3 error('unisensTools:missingArugments','Wrong number of Arguments.\nUsage:\nunisensBin2Csv(''path_to_unisens_bin_dataset\'') \nunisensBin2Csv(''path_to_unisens_bin_dataset\'', ''path_to_new_unisens_csv_dataset\'')'); end if nargin ==1 keepSensorScaling=true; new_path = [path '_csv']; end if nargin ==2 new_path = [path '_csv']; end %open unisens dataset j_unisensFactory = org.unisens.UnisensFactoryBuilder.createFactory(); j_unisens = j_unisensFactory.createUnisens(path); %create new unisens dataset j_unisens_new = j_unisensFactory.createUnisens(new_path); %set comment j_unisens_new.setComment([char(j_unisens.getComment()) ' Converted by unisensBin2Csv().']); %copy custom attibutes j_custom_attributes = j_unisens.getCustomAttributes(); j_key_iterator = j_custom_attributes.keySet().iterator(); while( j_key_iterator. hasNext() ) j_key = j_key_iterator.next(); j_unisens_new.addCustomAttribute(j_key,j_custom_attributes.get(j_key)); end %copy context information j_context = j_unisens.getContext(); if ~isempty(j_context) j_unisens_new.createContext(j_context.getSchemaUrl()); copyfile([path filesep 'context.xml'],new_path); end %set measurement id measurement_id = j_unisens.getMeasurementId(); if ~isempty(measurement_id) j_unisens_new.setMeasurementId(j_unisens.getMeasurementId()); end %set duration in [s] j_unisens_new.setDuration(j_unisens.getDuration()); %set timestamp in [s] j_timestamp_start = j_unisens.getTimestampStart(); if ~isempty(j_timestamp_start) j_unisens_new.setTimestampStart(j_timestamp_start); end %loop over all timed entries (signal, values and event entries) j_entries = j_unisens.getEntries(); nEntries = j_entries.size(); for i = 0:nEntries-1 j_entry = j_entries.get(i); entry_class_name= j_entry.getClass.toString; if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %here we go if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) %signalEntry signal_entry_convert(j_entry, j_unisens_new, keepSensorScaling); elseif (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) %valuesEntry values_entry_copy(j_entry, j_unisens_new); elseif (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %eventEntry event_entry_copy(j_entry, j_unisens_new); end elseif (strcmp(entry_class_name, 'class org.unisens.ri.CustomEntryImpl')) %customEntry disp('Crop not possible for custom Entries'); end end %copy groups j_groups = j_unisens.getGroups(); nGroups = j_groups.size(); for i = 0:nGroups-1 j_group = j_groups.get(i); j_group_cropped = j_unisens_new.createGroup(j_group.getId()); j_group_entries = j_group.getEntries(); nEntries = j_group.size(); for j = 0:nEntries j_group_cropped.addEntry(j_unisens_new.getEntry(j_group_entries.get(j).getId())); end end %unisens speichern j_unisens_new.save(); j_unisens_new.closeAll(); j_unisens.closeAll(); end function signal_entry_convert(j_entry, j_unisens_new, keepSensorScaling) %copy entry information newId = strrep(char(j_entry.getId()),'bin','csv'); if keepSensorScaling==true j_entry_new=j_unisens_new.createSignalEntry(newId, j_entry.getChannelNames, j_entry.getDataType() , j_entry.getSampleRate()); j_entry_new.setLsbValue(j_entry.getLsbValue()); j_entry_new.setBaseline(j_entry.getBaseline()); else j_entry_new=j_unisens_new.createSignalEntry(newId, j_entry.getChannelNames, org.unisens.DataType.DOUBLE , j_entry.getSampleRate()); end j_entry_new.setFileFormat(j_entry_new.createCsvFileFormat()); j_entry_new.setComment(j_entry.getComment()); j_entry_new.setContentClass(j_entry.getContentClass()); j_entry_new.setUnit(j_entry.getUnit()); %copy data piecewise position = 0; total = j_entry.getCount(); while (position < total) if (total - position > 1000000) count = 1000000; else count = total - position; end if keepSensorScaling==true data = j_entry.read(position, count); else data = j_entry.readScaled(position, count); end j_entry_new.append(data); position = position + count; end end function values_entry_copy(j_entry, j_unisens_new) j_entry_new=j_unisens_new.addEntry(j_entry.clone(),true); end function event_entry_copy(j_entry, j_unisens_new) j_entry_new=j_unisens_new.addEntry(j_entry.clone(),true); end
github
Unisens/unisensMatlabTools-master
unisensAddZerosEnd.m
.m
unisensMatlabTools-master/unisensAddZerosEnd.m
7,664
utf_8
c567890472a5e0394fdfe8d1e7a8fa5d
function unisensAddZerosEnd(path, new_path, addZeros_samplerate, end_samplestamp) %UNISENSADDZEROSEND adds zeros to the end of a unisens dataset % Copyright 2020 movisens GmbH, Germany addZeros_end_time = end_samplestamp / addZeros_samplerate; %open unisens dataset j_unisensFactory = org.unisens.UnisensFactoryBuilder.createFactory(); j_unisens = j_unisensFactory.createUnisens(path); %check if unisens dataset is long enough if ~durationOk(j_unisens, end_samplestamp / addZeros_samplerate) warning(['Unisens Dataset ' path ' is too long.']); end %create new unisens dataset j_unisens_addZeros = j_unisensFactory.createUnisens(new_path); %set comment j_unisens_addZeros.setComment([char(j_unisens.getComment()) ' Zeros added by addZerosEnd(). Small jitter possible']); %copy custom attibutes j_custom_attributes = j_unisens.getCustomAttributes(); j_key_iterator = j_custom_attributes.keySet().iterator(); while( j_key_iterator. hasNext() ) j_key = j_key_iterator.next(); j_unisens_addZeros.addCustomAttribute(j_key,j_custom_attributes.get(j_key)); end %copy context information j_context = j_unisens.getContext(); if ~isempty(j_context) j_unisens_addZeros.createContext(j_context.getSchemaUrl()); copyfile([path filesep 'context.xml'],new_path); end %set measurement id measurement_id = j_unisens.getMeasurementId(); if ~isempty(measurement_id) j_unisens_addZeros.setMeasurementId(j_unisens.getMeasurementId()); end %loop over all timed entries (signal, values and event entries) j_entries = j_unisens.getEntries(); nEntries = j_entries.size(); for i = 0:nEntries-1 j_entry = j_entries.get(i); entry_class_name= j_entry.getClass.toString; if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %here we go entry_samplerate= j_entries.get(i).getSampleRate(); entry_samplestamp_end = addZeros_end_time * entry_samplerate; if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) %signalEntry signal_entry_addZeros(j_entry, j_unisens_addZeros, entry_samplestamp_end); elseif (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) %valuesEntry %values_entry_addZeros(j_entry, j_unisens_addZeros, entry_samplestamp_end); elseif (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %eventEntry event_entry_addZeros(j_entry, j_unisens_addZeros, entry_samplestamp_end); end elseif (strcmp(entry_class_name, 'class org.unisens.ri.CustomEntryImpl')) %customEntry disp('Add zeros not possible for custom Entries'); end end %set new duration in [s] %TODO duration will be changed to double? j_unisens_addZeros.setDuration(addZeros_end_time) %set timesamtp start if available if ~isempty(j_unisens.getTimestampStart()) j_unisens_addZeros.setTimestampStart(j_unisens.getTimestampStart()); end %copy groups j_groups = j_unisens.getGroups(); nGroups = j_groups.size(); for i = 0:nGroups-1 j_group = j_groups.get(i); j_group_addZeros = j_unisens_addZeros.createGroup(j_group.getId()); j_group_entries = j_group.getEntries(); nEntries = j_group.size(); for j = 0:nEntries j_group_addZeros.addEntry(j_unisens_addZeros.getEntry(j_group_entries.get(j).getId())); end end %unisens speichern j_unisens_addZeros.save(); j_unisens_addZeros.closeAll(); j_unisens.closeAll(); end function signal_entry_addZeros(j_entry, j_unisens_addZeros, samplestamp_end) %copy entry information j_entry_addZeros=j_unisens_addZeros.addEntry(j_entry.clone(),false); %copy data piecewise position = 1; channels = 1; while (position < samplestamp_end) if (samplestamp_end - position > 1000000) count = 1000000; else count = samplestamp_end - position; end data = j_entry.read(position, count); if ~isempty(data) channels = size(data,2); j_entry_addZeros.append(data); if int64(length(data)) < int64(count) j_entry_addZeros.append(zeros(int64(count-length(data)),int64(channels),lower(char(j_entry.getDataType)))); end else j_entry_addZeros.append(zeros(int64(count),int64(channels),lower(char(j_entry.getDataType)))); end position = position + count; end end function values_entry_addZeros(j_entry, j_unisens_addZeros, samplestamp_end) j_entry_addZeros=j_unisens_addZeros.addEntry(j_entry.clone(),false); %copy values with timeshifted samplestamp while (true) j_values = j_entry.read(100000); nValues = j_values.size(); if nValues==0 break; end %TODO use arrayList of values for speed, add funtion to unisens %library for i=1:nValues j_value=j_values(i); if ~isempty(j_value) samplestamp = j_value.getSampleStamp(); if (samplestamp <=samplestamp_end) %TODO deep copy needed? j_value.setSamplestamp(j_value.getSamplestamp()); %j_value_addZeros = Value(j_value.getSamplestamp(), j_value.getData()); j_entry_addZeros.append(j_value); else %break if first value is outside region break; end else break; end end end end function event_entry_addZeros(j_entry, j_unisens_addZeros, samplestamp_end) j_unisens_addZeros=j_unisens_addZeros.addEntry(j_entry.clone(),false); %copy eventy with timeshifted samplestamp while (true) j_events = j_entry.read(100000); nEvents = j_events.size(); if nEvents==0 break; end j_event_iterator = j_events.iterator(); addZerosEvents = java.util.ArrayList(); while (j_event_iterator.hasNext()) j_event=j_event_iterator.next(); samplestamp = j_event.getSamplestamp(); if (samplestamp <=samplestamp_end) %TODO deep copy needed? %j_unisens_addZeros = org.unisens.Event(j_event.getSamplestamp(), j_event.getType(),j_event.getComment()); j_event.setSamplestamp(j_event.getSamplestamp()); addZerosEvents.add(j_event); else %break if first event is outside region break; end end j_unisens_addZeros.append(addZerosEvents); end end function result = durationOk(j_unisens, newDuration) j_entries = j_unisens.getEntries(); nEntries = j_entries.size(); allDurations = []; for i = 0:nEntries-1 j_entry = j_entries.get(i); entry_class_name= j_entry.getClass.toString; if strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl') nSamples=j_entry.getCount(); sampleRate = j_entry.getSampleRate(); allDurations=[allDurations nSamples/sampleRate]; end end result = min(allDurations) < newDuration; end
github
Unisens/unisensMatlabTools-master
unisensCsv2Bin.m
.m
unisensMatlabTools-master/unisensCsv2Bin.m
4,937
utf_8
93aaf329972417ca112b688c76105878
function unisensCsv2Bin(path, new_path) %UNISENSCSV2BIN convert unisens dataset with csv entries to dataset with bin entries % Converts all unisens signal entries from csv format (*.csv) to bin format (*.bin). % Event entries and values entries are not affected % Copyright 2017 movisens GmbH addUnisensJar(); if nargin==0 || nargin>2 error('unisensTools:missingArugments','Wrong number of Arguments.\nUsage:\nunisensCsv2Bin(''path_to_unisens_bin_dataset\'') \nunisensBin2Csv(''path_to_unisens_bin_dataset\'', ''path_to_new_unisens_csv_dataset\'')'); end if nargin ==1 new_path = [path '_bin']; end %open unisens dataset j_unisensFactory = org.unisens.UnisensFactoryBuilder.createFactory(); j_unisens = j_unisensFactory.createUnisens(path); %create new unisens dataset j_unisens_new = j_unisensFactory.createUnisens(new_path); %set comment j_unisens_new.setComment([char(j_unisens.getComment()) ' Converted by unisensCsv2Bin().']); %copy custom attibutes j_custom_attributes = j_unisens.getCustomAttributes(); j_key_iterator = j_custom_attributes.keySet().iterator(); while( j_key_iterator. hasNext() ) j_key = j_key_iterator.next(); j_unisens_new.addCustomAttribute(j_key,j_custom_attributes.get(j_key)); end %copy context information j_context = j_unisens.getContext(); if ~isempty(j_context) j_unisens_new.createContext(j_context.getSchemaUrl()); copyfile([path filesep 'context.xml'],new_path); end %set measurement id measurement_id = j_unisens.getMeasurementId(); if ~isempty(measurement_id) j_unisens_new.setMeasurementId(j_unisens.getMeasurementId()); end %set duration in [s] j_unisens_new.setDuration(j_unisens.getDuration()); %set timestamp in [s] j_timestamp_start = j_unisens.getTimestampStart(); if ~isempty(j_timestamp_start) j_unisens_new.setTimestampStart(j_timestamp_start); end %loop over all timed entries (signal, values and event entries) j_entries = j_unisens.getEntries(); nEntries = j_entries.size(); for i = 0:nEntries-1 j_entry = j_entries.get(i); entry_class_name= j_entry.getClass.toString; if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %here we go if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) %signalEntry signal_entry_convert(j_entry, j_unisens_new); elseif (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) %valuesEntry values_entry_copy(j_entry, j_unisens_new); elseif (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %eventEntry event_entry_copy(j_entry, j_unisens_new); end elseif (strcmp(entry_class_name, 'class org.unisens.ri.CustomEntryImpl')) %customEntry disp('Crop not possible for custom Entries'); end end %copy groups j_groups = j_unisens.getGroups(); nGroups = j_groups.size(); for i = 0:nGroups-1 j_group = j_groups.get(i); j_group_cropped = j_unisens_new.createGroup(j_group.getId()); j_group_entries = j_group.getEntries(); nEntries = j_group.size(); for j = 0:nEntries j_group_cropped.addEntry(j_unisens_new.getEntry(j_group_entries.get(j).getId())); end end %unisens speichern j_unisens_new.save(); j_unisens_new.closeAll(); j_unisens.closeAll(); end function signal_entry_convert(j_entry, j_unisens_new) %copy entry information newId = strrep(char(j_entry.getId()),'csv','bin'); j_entry_new=j_unisens_new.createSignalEntry(newId, j_entry.getChannelNames, org.unisens.DataType.DOUBLE , j_entry.getSampleRate()); j_entry_new.setFileFormat(j_entry_new.createBinFileFormat()); j_entry_new.setComment(j_entry.getComment()); j_entry_new.setContentClass(j_entry.getContentClass()); j_entry_new.setUnit(j_entry.getUnit()); %copy data piecewise position = 0; total = j_entry.getCount(); while (position < total) if (total - position > 1000000) count = 1000000; else count = total - position; end data = j_entry.readScaled(position, count); j_entry_new.append(data); position = position + count; end end function values_entry_copy(j_entry, j_unisens_new) j_entry_new=j_unisens_new.addEntry(j_entry.clone(),true); end function event_entry_copy(j_entry, j_unisens_new) j_entry_new=j_unisens_new.addEntry(j_entry.clone(),true); end
github
Unisens/unisensMatlabTools-master
unisensCrop.m
.m
unisensMatlabTools-master/unisensCrop.m
8,048
utf_8
f40ca68854d3743c34c1e1cdd289865a
function unisensCrop(path, new_path, crop_samplerate, start_samplestamp, end_samplestamp) %UNISENSCROP crop a unisens dataset to a specified region % Copyright 2017 movisens GmbH, Germany crop_start_time = start_samplestamp / crop_samplerate; crop_end_time = end_samplestamp / crop_samplerate; %check if crop_end_time is smaller than crop_start_time if start_samplestamp > end_samplestamp error('crop end is smaller than crop start'); end %open unisens dataset j_unisensFactory = org.unisens.UnisensFactoryBuilder.createFactory(); j_unisens = j_unisensFactory.createUnisens(path); %check if unisens dataset is long enough if ~durationOk(j_unisens, end_samplestamp / crop_samplerate) warning(['Unisens Dataset ' path ' is not long enough.']); end %create new unisens dataset j_unisens_cropped = j_unisensFactory.createUnisens(new_path); %set comment j_unisens_cropped.setComment([char(j_unisens.getComment()) ' Cropped by unisensCrop(). Small jitter possible']); %copy custom attibutes j_custom_attributes = j_unisens.getCustomAttributes(); j_key_iterator = j_custom_attributes.keySet().iterator(); while( j_key_iterator. hasNext() ) j_key = j_key_iterator.next(); j_unisens_cropped.addCustomAttribute(j_key,j_custom_attributes.get(j_key)); end %copy context information j_context = j_unisens.getContext(); if ~isempty(j_context) j_unisens_cropped.createContext(j_context.getSchemaUrl()); copyfile([path filesep 'context.xml'],new_path); end %set measurement id measurement_id = j_unisens.getMeasurementId(); if ~isempty(measurement_id) j_unisens_cropped.setMeasurementId(j_unisens.getMeasurementId()); end %loop over all timed entries (signal, values and event entries) j_entries = j_unisens.getEntries(); nEntries = j_entries.size(); for i = 0:nEntries-1 j_entry = j_entries.get(i); entry_class_name= j_entry.getClass.toString; if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) || ... (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %here we go entry_samplerate= j_entries.get(i).getSampleRate(); entry_samplestamp_start = crop_start_time * entry_samplerate; entry_samplestamp_end = crop_end_time * entry_samplerate; if (strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl')) %signalEntry signal_entry_crop(j_entry, j_unisens_cropped, entry_samplestamp_start, entry_samplestamp_end); elseif (strcmp(entry_class_name, 'class org.unisens.ri.ValuesEntryImpl')) %valuesEntry %values_entry_crop(j_entry, j_unisens_cropped, entry_samplestamp_start, entry_samplestamp_end); elseif (strcmp(entry_class_name, 'class org.unisens.ri.EventEntryImpl')) %eventEntry event_entry_crop(j_entry, j_unisens_cropped, entry_samplestamp_start, entry_samplestamp_end); end elseif (strcmp(entry_class_name, 'class org.unisens.ri.CustomEntryImpl')) %customEntry disp('Crop not possible for custom Entries'); end end %set new duration in [s] %TODO duration will be changed to double? j_unisens_cropped.setDuration(crop_end_time-crop_start_time) %set new timesamtp start if available j_timestamp_start = j_unisens.getTimestampStart(); if ~isempty(j_timestamp_start) j_unisens_cropped.setTimestampStart(java.util.Date(j_timestamp_start.getTime() + (crop_start_time*1000))); end %copy groups j_groups = j_unisens.getGroups(); nGroups = j_groups.size(); for i = 0:nGroups-1 j_group = j_groups.get(i); j_group_cropped = j_unisens_cropped.createGroup(j_group.getId()); j_group_entries = j_group.getEntries(); nEntries = j_group.size(); for j = 0:nEntries j_group_cropped.addEntry(j_unisens_cropped.getEntry(j_group_entries.get(j).getId())); end end %unisens speichern j_unisens_cropped.save(); j_unisens_cropped.closeAll(); j_unisens.closeAll(); end function signal_entry_crop(j_entry, j_unisens_cropped, samplestamp_start, samplestamp_end) %copy entry information j_entry_cropped=j_unisens_cropped.addEntry(j_entry.clone(),false); %copy data piecewise position = samplestamp_start; while (position < samplestamp_end) if (samplestamp_end - position > 1000000) count = 1000000; else count = samplestamp_end - position; end data = j_entry.read(position, count); if ~isempty(data) j_entry_cropped.append(data); end position = position + count; end end function values_entry_crop(j_entry, j_unisens_cropped, samplestamp_start, samplestamp_end) j_entry_cropped=j_unisens_cropped.addEntry(j_entry.clone(),false); %copy values with timeshifted samplestamp while (true) j_values = j_entry.read(100000); nValues = j_values.size(); if nValues==0 break; end %TODO use arrayList of values for speed, add funtion to unisens %library for i=1:nValues j_value=j_values(i); if ~isempty(j_value) samplestamp = j_value.getSampleStamp(); if (samplestamp > samplestamp_start) if (samplestamp <=samplestamp_end) %TODO deep copy needed? j_value.setSamplestamp(j_value.getSamplestamp()-samplestamp_start); %j_value_cropped = Value(j_value.getSamplestamp()-samplestamp_start, j_value.getData()); j_entry_cropped.append(j_value); else %break if first value is outside crop region break; end end else break; end end end end function event_entry_crop(j_entry, j_unisens_cropped, samplestamp_start, samplestamp_end) j_entry_cropped=j_unisens_cropped.addEntry(j_entry.clone(),false); %copy eventy with timeshifted samplestamp while (true) j_events = j_entry.read(100000); nEvents = j_events.size(); if nEvents==0 break; end j_event_iterator = j_events.iterator(); croppedEvents = java.util.ArrayList(); while (j_event_iterator.hasNext()) j_event=j_event_iterator.next(); samplestamp = j_event.getSamplestamp(); if (samplestamp > samplestamp_start) if (samplestamp <=samplestamp_end) %TODO deep copy needed? %j_event_cropped = org.unisens.Event(j_event.getSamplestamp()-samplestamp_start, j_event.getType(),j_event.getComment()); j_event.setSamplestamp(j_event.getSamplestamp()-samplestamp_start); croppedEvents.add(j_event); else %break if first event is outside crop region break; end end end j_entry_cropped.append(croppedEvents); end end function result = durationOk(j_unisens, minDuration) j_entries = j_unisens.getEntries(); nEntries = j_entries.size(); allDurations = []; for i = 0:nEntries-1 j_entry = j_entries.get(i); entry_class_name= j_entry.getClass.toString; if strcmp(entry_class_name, 'class org.unisens.ri.SignalEntryImpl') nSamples=j_entry.getCount(); sampleRate = j_entry.getSampleRate(); allDurations=[allDurations nSamples/sampleRate]; end end result = min(allDurations) > minDuration; end
github
lightyears1998/a-gzhu-coder-master
figure.m
.m
a-gzhu-coder-master/period/freshman/物理实验/变温粘滞系数的测定/figure.m
473
utf_8
66121fba75c6072fcbef078143902f7f
% 变温粘滞系数 Figure % nw = [.548, .469, .343, .222, .182]; t = [ 30, 35, 40, 45, 50]; function rslt = fun(var, data) rslt = var(1) * exp(-var(2) * data); endfunction var0 = [0 0]; P = lsqcurvefit(@fun, var0, t, nw); graphics_toolkit("gnuplot"); figure(); hold on; grid off; axis([25, 55, 0, 0.6]); plot(t, nw, '+', 'MarkerSize', 12); plot([25:1:55], fun(P, [25:1:55]), 'LineWidth', 5); print('figure.png', '-dpng'); hold off;
github
vitoruapt/lartkv5-master
matlab2opencv.m
.m
lartkv5-master/src/utils/human_leader/matlab/matlab2opencv.m
1,002
utf_8
faa2274109d4211d124825eeac37a400
%creates yaml file from matlab var, so it can be loaded by opencv function matlab2opencv( variable, fileName, flag) [rows cols] = size(variable); % Beware of Matlab's linear indexing variable = variable'; % Write mode as default if ( ~exist('flag','var') ) flag = 'w'; end if ( ~exist(fileName,'file') || flag == 'w' ) % New file or write mode specified file = fopen( fileName, 'w'); fprintf( file, '%%YAML:1.0\n'); else % Append mode file = fopen( fileName, 'a'); end % Write variable header fprintf( file, ' %s: !!opencv-matrix\n', inputname(1)); fprintf( file, ' rows: %d\n', rows); fprintf( file, ' cols: %d\n', cols); fprintf( file, ' dt: f\n'); fprintf( file, ' data: [ '); % Write variable data for i=1:rows*cols fprintf( file, '%.6f', variable(i)); if (i == rows*cols), break, end fprintf( file, ', '); if mod(i+1,4) == 0 fprintf( file, '\n '); end end fprintf( file, ']\n'); fclose(file);
github
vitoruapt/lartkv5-master
show_labels.m
.m
lartkv5-master/src/utils/human_leader/matlab/show_labels.m
1,338
utf_8
ab280e637c4213c23d1ea1b9786aec23
%compare the labels created by the three evaluators with, also plotting the %final tag, for illustrative purposes only. %input must be xx files function [] = plot_labels(test) features = test(:,5:end); low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); % Create figure F = figure('position',[360 260 900 600]); set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',1.5); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); %%%%%%%%%%% pro plot %%%%%%%%%% gd_class = test(:,2); bad_tag = test(gd_class == 1,1); H = figure; hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]); %axis equal; axis tight; ax_x = get(H, 'xlim'); ax_y = get(H, 'ylim'); box on; set(gca,'XTickLabel',[]); %set(gca,'YTickLabel',[]); ylabel('pro'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
vitoruapt/lartkv5-master
relative_velocities.m
.m
lartkv5-master/src/utils/human_leader/matlab/relative_velocities.m
901
utf_8
f9ecea158bfff8175dccdbc6bb95383f
%compute relative velocities, decomposing original feature that was scalar %only, requires target_velocity, relative_velocity and relative_heading function [rel_vx rel_vy] = relative_velocities(dataset) tgt_v = dataset(:,3); rel_v = dataset(:,4); rel_h = dataset(:,5); %recompute robot velocity robot_v = rel_v + tgt_v; %sin an cos of relative angle (heading) sin_v = sin(rel_h); cos_v = cos(rel_h); %compute target vel wrt robot frame tgt_vx = tgt_v.*cos_v; tgt_vy = tgt_v.*sin_v; %compute relative vel wrt robot frame rel_vx = tgt_vx - robot_v; rel_vy = tgt_vy; %rel_vx = tgt_v.*cos(rel_h) - (rel_v + tgt_v); %for comparison with rel_v from dataset %rel_v = sqrt(((robotv-tgt_vx).^2)+(tgt_vy).^2); % figure,hold % plot(rel_v,'b') % plot(abs(dataset(:,4)),'r') % plot(tgt_vx,'m') % plot(tgt_vy,'c') % plot(sin_v,'k') % plot(cos_v,'y') % % delta = abs(dataset(:,4))-rel_v; %plot(delta,'go') end
github
vitoruapt/lartkv5-master
plot_class_error.m
.m
lartkv5-master/src/utils/human_leader/matlab/plot_class_error.m
942
utf_8
293c87fc993554746f6e4632eebf2aec
%show the error in classification as a graph, for all the test set, shown %in the x axis, input is a matrix copied from excel, containing the value %of the errors, but could come directly from evaluate_model function. it %has been done this way because excel already had all the errors in tables. function [] = plot_class_error(input) F = figure; hold; set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',2); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); plot(input(1,:),'bs-','color',[1 0.82 0.13]); plot(input(2,:),'md-','color',[1 0.26 0.06]); plot(input(3,:),'ko-','color',[0 0.27 0.53]); label = {'st04','st08','gd02','gd06','as02','as03',... 'fr04','nm05','nm03','od01','od10','total'}; axis tight, grid on; set(gcf,'position',[175 338 1000 300]); set(gca,'ylim',[0 0.4]); set(gca,'xtick',1:12) set(gca,'XTickLabel',label); legend('false good','false bad','false total','location','eastoutside');
github
vitoruapt/lartkv5-master
show_thresholds.m
.m
lartkv5-master/src/utils/human_leader/matlab/show_thresholds.m
943
utf_8
7bdaa72b918d819190140d9908221b5d
%create linear variation of features to find what are the thresholds %used by the classifier on each feature, receive as argument the classifier %and the dimension to evaluate function []=show_thresholds(model,dim) clear new_model; clear j; j=1; clear test_thresh; % test_thresh = zeros(401,9); test_thresh(:,1) = 1:401; % second column is tag, does not matter here. test_thresh(:,3) = -10:0.05:10; %1 velocity % test_thresh(:,4) = -10:0.05:10; %2 lat disp. % test_thresh(:,5) = -pi:0.0157:pi; %3 rel head. % test_thresh(:,6) = -pi:0.0157:pi; %4 angle % test_thresh(:,7) = -10:0.05:10; %5 dist % test_thresh(:,8) = -10:0.05:10; %6 rel vx % test_thresh(:,9) = -10:0.05:10; %7 rel vy % % test_thresh(:,10:23) = 0; % for ii=10:23 % test_thresh(:,ii) = -10:0.05:10; % end for i=1:length(model) if model(i).dimension == dim new_model(j)=model(i); j=j+1; end end evaluate_model_single(new_model,test_thresh); end
github
vitoruapt/lartkv5-master
compare_classifiers.m
.m
lartkv5-master/src/utils/human_leader/matlab/compare_classifiers.m
3,391
utf_8
49da591a25df76b44b60c94c25ddbf32
% i think this was created to comparte an adaboost classificer with % a neural network classifier %test neural network function [] = compare_classifiers(model,net,test) %prepare the data features = test(:,3:7); input_val = features'; target_val = test(:,2)'; target_val(2,find(target_val == 0)) = 1; %for ann test(test(:,2)==0,2)=-1; %for ada: transform from 0 to -1 gd_class = test(:,2); %second column has leader tag %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); %%%%%%%%%%%%% ANN Classifier %%%%%%%%%% % Test the Network outputs = net(input_val); % binarize classification = good/bad ann_class = round(outputs(2,:)); %diferences = abs(test_class - gd_class); differences = abs(target_val(2,:) - ann_class); error = length(find(differences == 1)); error_ratio = error / length(differences); ann_string = ... sprintf('NeuralNet Classification. error:%.2f',error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% Adaboost Classifier %%%%%%%%%% % Classify the features with the trained model if(isstruct(model)) %classic adaboost ada_class = adaboost('apply',features, model); else %matlab adaboost ada_class = predict(model, features); end diferences = abs(ada_class - gd_class); error = length(find(diferences == 2)); error_ratio = error / length(diferences); ada_string = ... sprintf('Adaboost Classification. error:%.2f',error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% groundtruth plot %%%%%%%%%% bad_tag = test(gd_class == 1,1); % Show groundtruth H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',2); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); set(H,'position',[740 110 550 550]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot(3,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end vel = plot(time,features(:,1),'b'); vld = plot(time,features(:,2),'m'); hdd = plot(time,features(:,3),'k'); ang = plot(time,features(:,4),'g'); dst = plot(time,features(:,5),'y'); l_handle = legend([vel, vld, hdd, ang, dst],... 'vel','vel diff','head diff','angle', 'distance'); set(l_handle,'orientation','horizontal',... 'Position',[0.12 0.0 0.8 0.05]); axis tight; set(gca,'XTickLabel',[]); title('Ground Truth','FontWeight','bold'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% neural net plot %%%%%%%%%%% bad_tag = test(ann_class == 0,1); % Show classification subplot(3,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b'); plot(time,features(:,2),'m'); plot(time,features(:,3),'k'); plot(time,features(:,4),'g'); plot(time,features(:,5),'y'); axis tight; set(gca,'XTickLabel',[]); title(ann_string,'FontWeight','bold'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Adaboost plot %%%%%%%%%%%%% bad_tag = test(ada_class == 1,1); % Show classification subplot(3,1,3), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b'); plot(time,features(:,2),'m'); plot(time,features(:,3),'k'); plot(time,features(:,4),'g'); plot(time,features(:,5),'y'); axis tight; title(ada_string,'FontWeight','bold');
github
vitoruapt/lartkv5-master
train_net.m
.m
lartkv5-master/src/utils/human_leader/matlab/train_net.m
907
utf_8
0d219bb6a1a146ccf798b6ec9b25b86f
%train neural network % function [net] = train_net(inputs,targets) function [net] = train_net(train_set,n_neurons) inputs = train_set(:,3:end); targets = train_set(:,2); targets(targets==0,2)=1; % Solve a Pattern Recognition Problem with a Neural Network inputs = inputs'; targets = targets'; % Create a Pattern Recognition Network hiddenLayerSize = n_neurons;%[10,10]; net = patternnet(hiddenLayerSize); %net.performParam.regularization = 0.1; % net.trainFcn = 'trainbr'; net.trainParam.max_fail = 100; % Setup Division of Data for Training, Validation, Testing %net.divideFcn = 'dividetrain' net.divideFcn = 'divideind'; net.divideParam.testInd = []; net.divideParam.trainInd = 1:8504; net.divideParam.valInd = 8505:10196; % net.divideparam.trainratio = 85/100; % net.divideparam.valratio = 10/100; % net.divideparam.testratio = 5/100; % Train the Network [net,tr] = train(net,inputs,targets);
github
vitoruapt/lartkv5-master
test_net.m
.m
lartkv5-master/src/utils/human_leader/matlab/test_net.m
3,230
utf_8
8dc4a43efed1f2b19867805d622306f8
%test neural network function [] = test_net(net,test_set) for number = 1:length(test_set) test = test_set(number).set; name = test_set(number).name; %prepare the data features = test(:,3:end); input_val = features'; target_val = test(:,2)'; target_val(2,target_val == 0) = 1; gt_class = test(:,2); %second column has leader tag %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); % Test the Network outputs = net(input_val); %errors = gsubtract(y_val',outputs); %performance = perform(net,y_val',outputs) classes = round(outputs(2,:)); %classes = vec2ind(outputs) - 1; %%%%% debug plot %%%%%% % figure, hold; % plot(target_val','o'); % plot(outputs(1,:),'k'); % plot(outputs(2,:),'r'); % plot(classes,'y'); %diferences = abs(test_class - gd_class); % differences = abs(target_val(2,:)-classes); % error = length(find(differences == 1)); % error_ratio = error / length(differences); % title_string = ... % sprintf('NeuralNet Classification. error:%.2f',error_ratio); differences = classes - target_val(2,:); false_bad = length(find(differences == -1)); false_good = length(find(differences == 1)); false_total = false_bad + false_good; false_bad_ratio = false_bad / length(differences); false_good_ratio = false_good / length(differences); false_bad_ratio = round(false_bad_ratio*100)/100; false_good_ratio = round(false_good_ratio*100)/100; error_ratio = false_bad_ratio + false_good_ratio; title_string = ... sprintf('false good:%.2f, false bad:%.2f, total error:%.2f',... false_good_ratio, false_bad_ratio, error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% groundtruth plot %%%%%%%%%% bad_tag = test(gt_class == 1,1); % Show groundtruth figure; subplot(2,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); %axis equal; axis tight; title(['test:' name ' ' 'ground truth']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% classification plot %%%%%%% bad_tag = test(classes == 0,1); % Show classification subplot(2,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); plot(time,outputs(1,:),'bo'); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); %axis equal; axis tight; title(title_string); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end
github
vitoruapt/lartkv5-master
evaluate_model_single.m
.m
lartkv5-master/src/utils/human_leader/matlab/evaluate_model_single.m
3,609
utf_8
b86fe2360a8aafd9d15d87f1c08468b1
%evaluates adaboost classifier, comparing groundtruth %with class output, may receive a single dataset or a structure of them, %create plots comparing ground truth and classification, also prints error %of false good, false bad and false total function [] = evaluate_model(model,test_set) if size(test_set,1)~=1 temp = test_set; clear test_set; test_set.set = temp; test_set.name = 'single'; end for number = 1:length(test_set) test = test_set(number).set; name = test_set(number).name; %prepare the data features = test(:,3:end); test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test(:,2); %second column has leader tag [-1 good / 1 bad] %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); tic % Classify the features with the trained model if(isstruct(model)) %classic adaboost test_class=adaboost('apply',features, model); else %matlab adaboost test_class=predict(model, features); end toc differences = test_class - gd_class; false_bad = length(find(differences == 2)); false_good = length(find(differences == -2)); false_total = false_bad + false_good; false_bad_ratio = false_bad / length(differences); false_good_ratio = false_good / length(differences); false_bad_ratio = round(false_bad_ratio*100)/100; false_good_ratio = round(false_good_ratio*100)/100; error_ratio = false_bad_ratio + false_good_ratio; title_string = ... sprintf('false good:%.2f, false bad:%.2f, total error:%.2f',... false_good_ratio, false_bad_ratio, error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% target plot %%%%%%%%%%%%%%% bad_tag = test(gd_class == 1,1); % Show the data H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',2); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); subplot(2,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); axis tight; %axis equal title(['test:' name ' ' 'ground truth']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Show result bad_tag = test(test_class == 1,1); % Show the data subplot(2,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); axis tight; %axis equal; title(title_string); end end function large_markers tmp_l = legend('velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(tmp_l,'visible','off') xlabel('t(s)'); ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); %set(ax2,'position',get(ax1,'position')); hL = legend(ax2,'velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(ax2,'visible','off') axis(ax1, 'tight'); %set(gcf,'position',[200 200 800 400]); end
github
vitoruapt/lartkv5-master
adaboost_vs_ann.m
.m
lartkv5-master/src/utils/human_leader/matlab/adaboost_vs_ann.m
1,794
utf_8
2b9a6ca896a568cbfad96012f03beb47
%compare the labels created by the three evaluators with, also plotting the %final tag, for illustrative purposes only. function [] = adaboost_vs_ann() % Create figure % F = figure('position',[360 260 750 600]); F = figure('position',[360 260 750 500]); set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',1.5); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); %%%%%%%%%%% false good %%%%%%%%%% % FG = subplot(3,1,1,'position',[0.065 0.70 0.90 0.20]); FG = subplot(3,1,1,'position',[0.075 0.65 0.90 0.25]); hold on; grid on; set(gca,'xtick',1:12); set(FG,'xlim',[1 12]); set(FG,'ylim',[0 0.4]); ax_x = get(FG, 'xlim'); ax_y = get(FG, 'ylim'); box on; set(gca,'XTickLabel',[]); ylabel('false good'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% false bad %%%%%%%%%% % FB = subplot(3,1,2,'position',[0.065 0.4125 0.90 0.20]); FB = subplot(3,1,2,'position',[0.075 0.36 0.90 0.25]); hold on; grid on; set(gca,'xtick',1:12); set(FB,'xlim',ax_x); set(FB,'ylim',ax_y); set(gca,'XTickLabel',[]); box on; ylabel('false bad'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% false total %%%%%%%%%% FT = subplot(3,1,3,'position',[0.075 0.066 0.90 0.25]); hold on; grid on; set(gca,'xtick',1:12); set(FT,'xlim',ax_x); set(FT,'ylim',ax_y); box on; label = {'st04','st08','gd02','gd06','as02','as03',... 'fr04','nm05','nm03','od01','od10','total'}; set(gca,'XTickLabel',label); ylabel('false total'); large_markers %%%%%%%%%%%%%%%%%%%%%%%% end function large_markers ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'r','linewidth',10,'parent',ax2); hL = legend(ax2,'AdaBoost','ANN','location','eastOutside'); set(hL,'orientation', 'horizontal'); set(hL,'position', [0.37 0.92 0.25 0.05]); set(ax2,'visible','off') axis(ax1, 'tight'); end
github
vitoruapt/lartkv5-master
train_adaboost.m
.m
lartkv5-master/src/utils/human_leader/matlab/train_adaboost.m
5,522
utf_8
2362578a48eadb03855f3d3a151234ea
%trains an adaboost classifier, input is training set, and iterations are %the max number of weak classifiers allowed function [classestimate,model,feat_of_wc] = train_adaboost(data,iterations) %train adaboost classifier downloaded from internet %features: % 3: target velocity % 4: lateral displacement (former relative velocity) % 5: heading difference % 6: angle between robot head and target pos % 7: distance % 8: relative velocity x % 9: relative velocity y datafeatures = data(:,3:end); % data classification data(data(:,2)==0,2)=-1; %transform from 0 to -1 dataclass = data(:,2); %second column has leader tag % Use Adaboost to make a classifier [classestimate,model]=adaboost('train',datafeatures,dataclass,iterations); % Show the error verus number of weak classifiers error=zeros(1,length(model)); feat_of_wc = zeros(1,length(model)); cont_ratio = zeros(1,size(datafeatures,2)); for i=1:length(model) error(i)=model(i).error; feature_id = model(i).dimension; feat_of_wc(i) = feature_id; cont_ratio(feature_id)=cont_ratio(feature_id)+model(i).alpha; end cont_ratio = cont_ratio./sum(cont_ratio); fh1 = figure; set(fh1,'defaultlinelinewidth',3); set(fh1,'defaultaxeslinewidth',2); set(fh1,'defaulttextfontsize',12); set(fh1,'defaultaxesfontsize',12); set(fh1,'position',[480 210 800 400]); hold, title('Classification error versus number of weak classifiers'); plot(error); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fh2 = figure; set(fh2,'defaultlinelinewidth',3); set(fh2,'defaultaxeslinewidth',2); set(fh2,'defaulttextfontsize',12); set(fh2,'defaultaxesfontsize',12); set(fh2,'position',[ 679 106 600 400]); hold, title('Features'); % [H,X] = hist(feat_of_wc,1:size(datafeatures,2)); [H,X] = hist(feat_of_wc,1:size(datafeatures,2)); a = [H;X]'; a(:,3) = a(:,1)/length(feat_of_wc); sortrows(a) cm = jet(length(X)); for i=1:length(X) h=bar(X(i),H(i)); set(h,'facecolor',cm(i,:)); end ylabel('weak classifiers'); set(gca,'XTickLabel',[]); axis tight; % legend('velocity',... % 'lateral displacement',... % 'relative heading',... % 'angle','distance',... % 'relative vel. x',... % 'relative vel. y',... % 'location','eastOutside'); legend('mean target vel.',... 'mean lat. displ.',... 'mean rel. head.',... 'mean angle',... 'mean distance',... 'mean relative vel. x',... 'mean relative vel. y',... 'Location','eastOutside') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fh3 = figure; set(fh3,'defaultlinelinewidth',3); set(fh3,'defaultaxeslinewidth',2); set(fh3,'defaulttextfontsize',12); set(fh3,'defaultaxesfontsize',12); set(fh3,'position',[ 679 106 600 400]); hold, title({'Features Contribution Ratio';... sprintf('(number of weak classifiers = %i)',length(feat_of_wc))}) %X = 1:length(cont_ratio); H = cont_ratio; cm = jet(length(X)); for i=1:length(X) h2=bar(X(i),H(i)); set(h2,'facecolor',cm(i,:)); end ylabel('contribution ratio'); set(gca,'XTick',1:21); set(gcf,'position',[250 100 1200 500]); axis tight; set(gca,'YLim',[0 0.25]); grid; legend('1. lateral displ.',... '2. rel. heading',... '3. angle',... '4. distance',... '5. stdv distance',... 'Location','eastOutside'); legend('1. target velocity',... '2. lateral displ.',... '3. rel. heading',... '4. angle',... '5. distance',... '6. relative vel. x',... '7. relative vel. y',... '8. stdv target vel.',... '9. stdv lateral displ.',... '10. stdv rel. head.',... '11. stdv angle',... '12. stdv distance',... '13. stdv relative vel. x',... 'Location','eastOutside'); % if (length(H)~=length(X)) % X = [1 round(X)] % end a = [H;X]'; sortrows(a) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % legend('1. target velocity',... % '2. lateral displ.',... % '3. rel. heading',... % '4. angle',... % '5. distance',... % '6. relative vel. x',... % '7. relative vel. y',... % '8. \Delta target vel.',... % '9. \Delta lateral displ.',... % '10. \Delta rel. head.',... % '11. \Delta angle',... % '12. \Delta distance',... % '13. \Delta relative vel. x',... % '14. \Delta relative vel. y',... % '15. stdv target vel.',... % '16. stdv lateral displ.',... % '17. stdv rel. head.',... % '18. stdv angle',... % '19. stdv distance',... % '20. stdv relative vel. x',... % '21. stdv relative vel. y',... % 'Location','eastOutside'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Training results % Show results % blue=datafeatures(classestimate==-1,:); red=datafeatures(classestimate==1,:); % I=zeros(161,161); % for i=1:length(model) % if(model(i).dimension==1) % if(model(i).direction==1), rec=[-80 -80 80+model(i).threshold 160]; % else rec=[model(i).threshold -80 80-model(i).threshold 160 ]; % end % else % if(model(i).direction==1), rec=[-80 -80 160 80+model(i).threshold]; % else rec=[-80 model(i).threshold 160 80-model(i).threshold]; % end % end % rec=round(rec); % y=rec(1)+81:rec(1)+81+rec(3); x=rec(2)+81:rec(2)+81+rec(4); % I=I-model(i).alpha; I(x,y)=I(x,y)+2*model(i).alpha; % end % subplot(2,2,2), imshow(I,[]); colorbar; axis xy; % colormap('jet'), hold on % plot(blue(:,1)+81,blue(:,2)+81,'bo'); % plot(red(:,1)+81,red(:,2)+81,'ro'); % title('Training Data classified with adaboost model');
github
vitoruapt/lartkv5-master
leader_features.m
.m
lartkv5-master/src/utils/human_leader/matlab/leader_features.m
3,099
utf_8
55c282a169e38696d0583e4ede61126d
%extract features from chosen target and %stores it in a matlab variable (proc_target) %must pass as arguments the name of the file, generated by ROS %log file from process_target, and the id of the desired subject function [proc_target]=leader_features(file,target_id) % input file format: % 1: id % 2: good/bad tag % 3: time % 4: pos x % 5: pos y % 6: vel % 7: theta % 8: pos diff % 9: head diff %10: angle 2 robot %11: velocity diff %printf("%d,%d,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f\n", % target_id, badLeader, time_elapsed.toSec(), % target_x, target_y, target_vel, target_theta, % position_diff, heading_diff, angle_to_robot, velocity_diff); % output file format: % 1: time % 2: good/bad tag % 3: mean vel 1 % 4: mean vel diff 2 % 5: mean head diff 3 % 6: angle 2 robot 4 % 7: mean dist 2 robot 5 %initialize vars begin_sweep = 1; end_sweep = 1; counter = 1; mean_fig = figure; hold on; grid on; %load and rearrange targets file list = load(file); range = max(list(:,1)) + 2; cm = jet(range); figure,hold; for i = 1:length(list); if(list(i,1)==-1) plot3(list(i,4),list(i,5),list(i,3),'bo'); elseif(list(i,1)==target_id) plot3(list(i,4),list(i,5),list(i,3),'ro'); end end list = sortrows(list); % separate target from robot while counter < length(list) while list(begin_sweep,1) == list(end_sweep,1) end_sweep = end_sweep + 1; counter = counter + 1; if counter > length(list) break end end %only pick one target, according to input of function switch list(begin_sweep,1) case -1 robot = list(begin_sweep:end_sweep-1,:); case target_id target = list(begin_sweep:end_sweep-1,:); end begin_sweep = end_sweep; end % filter data proc_target(length(target),7) = 0; proc_target(:,1) = target(:,3); proc_target(:,2) = target(:,2); proc_target(:,3) = target(:,6); %vel proc_target(:,4) = target(:,11); %vel diff proc_target(:,5) = target(:,9); %head diff proc_target(:,6) = target(:,10); %angle 2 robot proc_target(:,7) = target(:,8); %pos diff (dist) %%%%%%%%% PLOTTING %%%%%%%%%%%% %plot good/bad leader index tag = find(diff(proc_target(:,2))); figure(mean_fig); plot(proc_target(:,1),proc_target(:,3),'b-'); plot(proc_target(:,1),proc_target(:,4),'r-'); plot(proc_target(:,1),proc_target(:,5),'k-'); plot(proc_target(:,1),proc_target(:,6),'g-'); plot(proc_target(:,1),proc_target(:,7),'y-'); legend('vel','vel diff','head diff','angle', 'distance',... 'Location','NorthWest'); title('mean features from target 2 robot'); if ~isempty(tag) line([proc_target(tag,1) proc_target(tag,1)],[0 5]) end figure(mean_fig); plot(proc_target(:,1),proc_target(:,3),'bo'); plot(proc_target(:,1),proc_target(:,4),'ro'); plot(proc_target(:,1),proc_target(:,5),'ko'); plot(proc_target(:,1),proc_target(:,6),'go'); plot(proc_target(:,1),proc_target(:,7),'yo'); legend('vel','vel diff','head diff','angle', 'distance',... 'Location','NorthWest');
github
vitoruapt/lartkv5-master
plot_labels.m
.m
lartkv5-master/src/utils/human_leader/matlab/plot_labels.m
4,314
utf_8
ebee9d9693bb54f2e92624c850c4223d
%compare the labels created by the three evaluators with, also plotting the %final tag, for illustrative purposes only. function [] = plot_labels(test,final_tag) features = test(:,5:end); low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); % Create figure F = figure('position',[360 260 900 600]); set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',1.5); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); %%%%%%%%%%% pro plot %%%%%%%%%% gd_class = test(:,2); bad_tag = test(gd_class == 1,1); H = subplot(3,1,1,'position',[0.065 0.70 0.70 0.20]); hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]); %axis equal; axis tight; ax_x = get(H, 'xlim'); ax_y = get(H, 'ylim'); box on; set(gca,'XTickLabel',[]); %set(gca,'YTickLabel',[]); ylabel('pro'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% rich plot %%%%%%%%%% gd_class = test(:,3); %rich tag bad_tag = test(gd_class == 1,1); % Show the data I = subplot(3,1,2,'position',[0.065 0.4125 0.70 0.20]); hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]); %axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); set(gca,'XTickLabel',[]); box on; %set(gca,'YTickLabel',[]); ylabel('rich'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% jor plot %%%%%%%%%% gd_class = test(:,4); %jorge_tag bad_tag = test(gd_class == 1,1); % Show the data I = subplot(3,1,3,'position',[0.065 0.1250 0.70 0.20]); hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]);%axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); box on; xlabel('t(s)'); %set(gca,'YTickLabel',[]); ylabel('jor'); large_markers %%%%%%%%%%%%%%%%%%%%%%%%%%% p_tag = test(diff(test(:,2))==1,1); r_tag = test(diff(test(:,3))==1,1); j_tag = test(diff(test(:,4))==1,1); [p_tag r_tag j_tag] %%%%%%%%%%%%%%%%%%%%%%%% end function large_markers xlabel('t(s)'); ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); plot(0,0,'color',[0.7 0.7 0.7],'linewidth',10,'parent',ax2); % hL = legend(ax2,'velocity','rel velocity',... % 'rel heading','angle','distance','bad leader region',... % 'final tag',... % 'location','eastOutside'); hL = legend(ax2,'velocity (m/s)','lateral disp. (m)',... 'relative head. (rad)','angle (rad)','distance (m)',... 'relative vel. x (m/s)','relative vel. y (m/s)','cropped region',... 'location','eastOutside'); set(hL,'position', [0.80 0.35 0.15 0.30]); set(ax2,'visible','off') axis(ax1, 'tight'); end
github
vitoruapt/lartkv5-master
plot_test2.m
.m
lartkv5-master/src/utils/human_leader/matlab/plot_test2.m
2,313
utf_8
968d8618023c1cc38d47190720487c42
%used in do_tag to show comparison between labels function [] = plot_test2(test_a) features = test_a(:,5:end); %test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test_a(:,2); %second column has leader tag low_plot = min(min(features)); up_plot = max(max(features)); time = test_a(:,1); bad_tag = test_a(gd_class == 1,1); % Show the data F = figure; set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',2); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); H = subplot(3,1,1); hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[0.5 0.5 0.5]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); %axis equal; axis tight; ax_x = get(H, 'xlim'); ax_y = get(H, 'ylim'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% features = test_a(:,5:end); %test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test_a(:,3); %rich tag low_plot = min(min(features)); up_plot = max(max(features)); time = test_a(:,1); bad_tag = test_a(gd_class == 1,1); % Show the data I = subplot(3,1,2); hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[0.5 0.5 0.5]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); %axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% features = test_a(:,5:end); %test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test_a(:,4); %jorge_tag low_plot = min(min(features)); up_plot = max(max(features)); time = test_a(:,1); bad_tag = test_a(gd_class == 1,1); % Show the data I = subplot(3,1,3); hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[0.5 0.5 0.5]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); %axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); xlabel('t(s)'); %%%%%%%%%%%%%%%%%%%%%%%%%%% p_tag = test_a(diff(test_a(:,2))==1,1); r_tag = test_a(diff(test_a(:,3))==1,1); j_tag = test_a(diff(test_a(:,4))==1,1); [p_tag r_tag j_tag]
github
vitoruapt/lartkv5-master
enhance_features.m
.m
lartkv5-master/src/utils/human_leader/matlab/enhance_features.m
4,253
utf_8
891a77b7a8827b581b59f2bf33af6c4e
%compute new features based on existing ones % % derivatives from position 10 to 16 % standard deviation, based on winsize, position 17 to 23 % mean, based on winsize, position 24 to 30 % % in final part, must uncomment the desired set, using only portions of % the features computed, eliminating features with reduced contribution % for example % % % 3 velocity % 4 lateral displacement % 5 relative heading % 6 angle 2 robot % 7 distance % 8 relative velocity x % 9 relative velocity y function new_features = enhance_features(input_features) new_features = input_features; % diff part new_features(2:end,10) = diff(input_features(:,3)); new_features(2:end,11) = diff(input_features(:,4)); new_features(2:end,12) = diff(input_features(:,5)); new_features(2:end,13) = diff(input_features(:,6)); new_features(2:end,14) = diff(input_features(:,7)); new_features(2:end,15) = diff(input_features(:,8)); new_features(2:end,16) = diff(input_features(:,9)); new_features(1,10) = new_features(2,10); new_features(1,11) = new_features(2,11); new_features(1,12) = new_features(2,12); new_features(1,13) = new_features(2,13); new_features(1,14) = new_features(2,14); new_features(1,15) = new_features(2,15); new_features(1,16) = new_features(2,16); % mean and stdv part for i = 1:length(input_features) winsize = 30; while(i-winsize <= 0) %not enough past info winsize = winsize - 1; end % stdv part new_features(i,17) = std(input_features(i-winsize:i,3)); %std vel new_features(i,18) = std(input_features(i-winsize:i,4)); %std lat. disp. new_features(i,19) = std(input_features(i-winsize:i,5)); %std rel. head. new_features(i,20) = std(input_features(i-winsize:i,6)); %std angle 2 robot new_features(i,21) = std(input_features(i-winsize:i,7)); %std dist new_features(i,22) = std(input_features(i-winsize:i,8)); %std rel v x new_features(i,23) = std(input_features(i-winsize:i,8)); %std rel v y % mean part new_features(i,24) = mean(input_features(i-winsize:i,3)); %mean vel new_features(i,25) = mean(input_features(i-winsize:i,4)); %mean lat. disp. new_features(i,26) = mean(input_features(i-winsize:i,5)); %mean rel. head new_features(i,27) = mean(input_features(i-winsize:i,6)); %mean angle 2 robot new_features(i,28) = mean(input_features(i-winsize:i,7)); %mean dist new_features(i,29) = mean(input_features(i-winsize:i,8)); %mean rel v x new_features(i,30) = mean(input_features(i-winsize:i,9)); %mean rel v y end % %test single feature thresholds % new_features = [new_features(:,1:2)... % new_features(:,7)]; %test integration with opencv adaboost % new_features = [new_features(:,1:2)... % new_features(:,3:7)]; % %test vel, lat dist., dist % new_features = [new_features(:,1:2)... % new_features(:,3)... % new_features(:,4)... % new_features(:,7)... % ]; % %reduced4 (lat. displ., dist., stdv distance) % new_features = [new_features(:,1:2)... % new_features(:,4)... % new_features(:,7)... % new_features(:,21)... % ]; % %reduced3 ODNM (minus relvx, relvy, stdv ld, stdv dist) % new_features = [new_features(:,1:2)... % new_features(:,3:7)... % ]; % %reduced3 (lat. displ., rel. heading, angle, dist. stdv distance) % new_features = [new_features(:,1:2)... % new_features(:,4:7)... % new_features(:,21)... % ]; %reduced2 == ODNM % new_features = [new_features(:,1:2)... % new_features(:,3:9)... % new_features(:,17)... % new_features(:,21)... % ]; % %reduced1 (no diff, no stdv rel_v_y) % new_features = [new_features(:,1:2)... % new_features(:,3:9)... % new_features(:,17:22)... % ]; % %train complete new_features = [new_features(:,1:2)... new_features(:,3:9)... new_features(:,10:16)... new_features(:,17:23)... ]; % %train no diff % new_features = [new_features(:,1:2)... % new_features(:,3:9)... % new_features(:,17:23)... % ]; %with mean % new_features = [new_features(:,1:2)... % new_features(:,3:9)... %kf output % new_features(:,10:16)... %diff % new_features(:,17:23)... %stdv % new_features(:,24:30)... %mean % ]; %only one % new_features = [new_features(:,1:2)... % new_features(:,3)];
github
vitoruapt/lartkv5-master
new_features.m
.m
lartkv5-master/src/utils/human_leader/matlab/new_features.m
263
utf_8
64fbb408c530fb0bd97e9027cb513024
%decompose relative velocity in x and y, compute lateral displacement function [out]=new_features(in) out = in; [rel_vel_x rel_vel_y] = relative_velocities(in); out(:,8) = rel_vel_x; out(:,9) = rel_vel_y; out(:,4) = sin(in(:,6)).*in(:,7); %put ld in place of rv
github
vitoruapt/lartkv5-master
crop_features.m
.m
lartkv5-master/src/utils/human_leader/matlab/crop_features.m
1,981
utf_8
a3fc318bef5c147ab0e5fb5c62756f4f
%crop variable containing leader features %so transitory measurments from beginning and %end can be removed %inputs: %in_data : input data %x1: inferior crop limit %x2: superior crop limit function [out_data] = crop_features(in_data,x1,x2) % Show the data H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',1.5); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); hold on, grid on; title('Cropped Fatures'); set(gcf,'position',[200 200 800 300]); [val1 ind1] = min(abs(in_data(:,1)-x1)); [val2 ind2] = min(abs(in_data(:,1)-x2)); top = max(max(in_data(:,3:9))); bottom = min(min(in_data(:,3:9))); patch([x1 x1 x2 x2],... [bottom top top bottom],... [0.7 0.7 0.7]);%,'faceAlpha',0.5); plot(in_data(:,1),in_data(:,3),'bo'); plot(in_data(:,1),in_data(:,4),'co'); plot(in_data(:,1),in_data(:,5),'ko'); plot(in_data(:,1),in_data(:,6),'go'); plot(in_data(:,1),in_data(:,7),'yo'); plot(in_data(:,1),in_data(:,8),'mo'); plot(in_data(:,1),in_data(:,9),'o','color',[0.5 0 0]); legend('vel','vel diff','head diff','angle', 'dist diff',... 'Location','eastOutside'); xlabel('t(s)'); axis tight; out_data = in_data(ind1:ind2,:); %large markers ax1 = gca; ax2 = axes('position',get(ax1,'position')); hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); plot(0,0,'color',[0.7 0.7 0.7],'linewidth',10,'parent',ax2); %set(ax2,'position',get(ax1,'position')); HL = legend(ax2,'velocity (m/s)','lateral disp. (m)',... 'relative head. (rad)','angle (rad)','distance (m)',... 'relative vel. x (m/s)','relative vel. y (m/s)','cropped region',... 'location','eastOutside'); set(HL,'position',[0.7650 0.35 0.23 0.37]); set(ax2,'visible','off') %axis(ax1, 'tight');
github
vitoruapt/lartkv5-master
do_tag.m
.m
lartkv5-master/src/utils/human_leader/matlab/do_tag.m
1,227
utf_8
19d31561f6a92e6f273b5b9fa70294a9
%new tag and shift time %as tests have different initial times, this function put all of them %in the same reference frame. the offsets are computed based on the %recorded images, because they have the correct time %first the tags are obatined using rxbag, then the first image of each %bag is compared wrt their clock stamp, the difference is the offset %normally the problem that created this differences has been solved, %and this would not be required for new bags and tests function [new_var] = do_tag(input_var, pro_tag, rich_tag, jor_tag,offset,off_j) %shift i = diff(input_var(:,2))==1; old_time = input_var(i,1); if(isempty(old_time)) time_diff = pro_tag; else time_diff = pro_tag - old_time; end new_var = input_var; new_var(:,1) = new_var(:,1) + time_diff; %new tag rich [val pos] = min(abs(new_var(:,1) - (rich_tag -offset))); class_rich = zeros(length(input_var),1); class_rich(pos:end)=1; if(rich_tag==99) class_rich(end)=0; end %new tag jor [val pos] = min(abs(new_var(:,1) - (jor_tag -offset-off_j))); class_jor = zeros(length(input_var),1); class_jor(pos:end)=1; if(rich_tag==99) class_jor(end)=0; end new_var = [new_var(:,1:2) class_rich class_jor new_var(:,3:end)]; plot_test2(new_var);
github
vitoruapt/lartkv5-master
evaluate_model.m
.m
lartkv5-master/src/utils/human_leader/matlab/evaluate_model.m
5,501
utf_8
ecf0d85ca58f00874687aa0be33c94df
%evaluates adaboost classifier, comparing groundtruth %with class output, may receive a single dataset or a structure of them, %create plots comparing ground truth and classification, also prints error %of false good, false bad and false total function [] = evaluate_model(model,test_set) if size(test_set,1)~=1 temp = test_set; clear test_set; test_set.set = temp; test_set.name = 'single'; end for number = 1:length(test_set) test = test_set(number).set; name = test_set(number).name; %prepare the data features = test(:,3:end); test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test(:,2); %second column has leader tag [-1 good / 1 bad] %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); tic % Classify the features with the trained model if(isstruct(model)) %classic adaboost test_class=adaboost('apply',features, model); else %matlab adaboost test_class=predict(model, features); end toc differences = test_class - gd_class; false_bad = length(find(differences == 2)); false_good = length(find(differences == -2)); false_total = false_bad + false_good; false_bad_ratio = false_bad / length(differences); false_good_ratio = false_good / length(differences); % error_ratio = false_total / length(differences); false_bad_ratio = round(false_bad_ratio*100)/100; false_good_ratio = round(false_good_ratio*100)/100; error_ratio = false_bad_ratio + false_good_ratio; % error_ratio = round(error_ratio*100)/100; title_string = ... sprintf('false good:%.2f, false bad:%.2f, total error:%.2f',... false_good_ratio, false_bad_ratio, error_ratio); %title_string = ['test:' name ' ' title_string]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% target plot %%%%%%%%%%%%%%% bad_tag = test(gd_class == 1,1); % Show the data H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',2); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); subplot(2,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'color',[0.5 0 0]); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); axis tight; %axis equal title(['test:' name ' ' 'ground truth']); % large_markers; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Show result bad_tag = test(test_class == 1,1); % Show the data subplot(2,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'color',[0.5 0 0]); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); axis tight; %axis equal; title(title_string); % large_markers; end %set(gcf,'position',[200 200 800 400]); score(length(test_class)-1)=0; for i=1:length(test_class) if test_class(i)==-1 vote = 0.01; else vote = -0.5; end score(i+1) = score(i) + vote; if score(i+1) > 1 score(i+1) = 1; elseif score(i+1) < -0.1 score(i+1) = -0.1; end end X = figure; hold; set(X,'position',[200 400 800 300]); set(X,'defaultlinelinewidth',3); set(X,'defaultaxeslinewidth',2); set(X,'defaulttextfontsize',12); set(X,'defaultaxesfontsize',12); line([bad_tag bad_tag],[-0.1 1],'Color',[1 0 0.1]); score = score(1:end-1); sc = plot(time,score); l1 = line([time(1) time(end)],[0 0],'Color',[1 0 0.1]); l2 = line([time(1) time(end)],[0 0],'Color',[0 0 0]); legend([l1, sc, l2],'bad leader','leader score','threshold',... 'location','eastoutside'); axis tight; xlabel('time (s)'), ylabel('score'); end function large_markers tmp_l = legend('velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(tmp_l,'visible','off') xlabel('t(s)'); ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); %set(ax2,'position',get(ax1,'position')); hL = legend(ax2,'velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(ax2,'visible','off') axis(ax1, 'tight'); %set(gcf,'position',[200 200 800 400]); end
github
vitoruapt/lartkv5-master
show_labels.m
.m
lartkv5-master/src/utils/process_target/matlab/show_labels.m
1,338
utf_8
ab280e637c4213c23d1ea1b9786aec23
%compare the labels created by the three evaluators with, also plotting the %final tag, for illustrative purposes only. %input must be xx files function [] = plot_labels(test) features = test(:,5:end); low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); % Create figure F = figure('position',[360 260 900 600]); set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',1.5); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); %%%%%%%%%%% pro plot %%%%%%%%%% gd_class = test(:,2); bad_tag = test(gd_class == 1,1); H = figure; hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]); %axis equal; axis tight; ax_x = get(H, 'xlim'); ax_y = get(H, 'ylim'); box on; set(gca,'XTickLabel',[]); %set(gca,'YTickLabel',[]); ylabel('pro'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
vitoruapt/lartkv5-master
show_thresholds.m
.m
lartkv5-master/src/utils/process_target/matlab/show_thresholds.m
943
utf_8
7bdaa72b918d819190140d9908221b5d
%create linear variation of features to find what are the thresholds %used by the classifier on each feature, receive as argument the classifier %and the dimension to evaluate function []=show_thresholds(model,dim) clear new_model; clear j; j=1; clear test_thresh; % test_thresh = zeros(401,9); test_thresh(:,1) = 1:401; % second column is tag, does not matter here. test_thresh(:,3) = -10:0.05:10; %1 velocity % test_thresh(:,4) = -10:0.05:10; %2 lat disp. % test_thresh(:,5) = -pi:0.0157:pi; %3 rel head. % test_thresh(:,6) = -pi:0.0157:pi; %4 angle % test_thresh(:,7) = -10:0.05:10; %5 dist % test_thresh(:,8) = -10:0.05:10; %6 rel vx % test_thresh(:,9) = -10:0.05:10; %7 rel vy % % test_thresh(:,10:23) = 0; % for ii=10:23 % test_thresh(:,ii) = -10:0.05:10; % end for i=1:length(model) if model(i).dimension == dim new_model(j)=model(i); j=j+1; end end evaluate_model_single(new_model,test_thresh); end
github
vitoruapt/lartkv5-master
compare_classifiers.m
.m
lartkv5-master/src/utils/process_target/matlab/compare_classifiers.m
3,391
utf_8
49da591a25df76b44b60c94c25ddbf32
% i think this was created to comparte an adaboost classificer with % a neural network classifier %test neural network function [] = compare_classifiers(model,net,test) %prepare the data features = test(:,3:7); input_val = features'; target_val = test(:,2)'; target_val(2,find(target_val == 0)) = 1; %for ann test(test(:,2)==0,2)=-1; %for ada: transform from 0 to -1 gd_class = test(:,2); %second column has leader tag %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); %%%%%%%%%%%%% ANN Classifier %%%%%%%%%% % Test the Network outputs = net(input_val); % binarize classification = good/bad ann_class = round(outputs(2,:)); %diferences = abs(test_class - gd_class); differences = abs(target_val(2,:) - ann_class); error = length(find(differences == 1)); error_ratio = error / length(differences); ann_string = ... sprintf('NeuralNet Classification. error:%.2f',error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% Adaboost Classifier %%%%%%%%%% % Classify the features with the trained model if(isstruct(model)) %classic adaboost ada_class = adaboost('apply',features, model); else %matlab adaboost ada_class = predict(model, features); end diferences = abs(ada_class - gd_class); error = length(find(diferences == 2)); error_ratio = error / length(diferences); ada_string = ... sprintf('Adaboost Classification. error:%.2f',error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% groundtruth plot %%%%%%%%%% bad_tag = test(gd_class == 1,1); % Show groundtruth H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',2); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); set(H,'position',[740 110 550 550]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot(3,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end vel = plot(time,features(:,1),'b'); vld = plot(time,features(:,2),'m'); hdd = plot(time,features(:,3),'k'); ang = plot(time,features(:,4),'g'); dst = plot(time,features(:,5),'y'); l_handle = legend([vel, vld, hdd, ang, dst],... 'vel','vel diff','head diff','angle', 'distance'); set(l_handle,'orientation','horizontal',... 'Position',[0.12 0.0 0.8 0.05]); axis tight; set(gca,'XTickLabel',[]); title('Ground Truth','FontWeight','bold'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% neural net plot %%%%%%%%%%% bad_tag = test(ann_class == 0,1); % Show classification subplot(3,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b'); plot(time,features(:,2),'m'); plot(time,features(:,3),'k'); plot(time,features(:,4),'g'); plot(time,features(:,5),'y'); axis tight; set(gca,'XTickLabel',[]); title(ann_string,'FontWeight','bold'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Adaboost plot %%%%%%%%%%%%% bad_tag = test(ada_class == 1,1); % Show classification subplot(3,1,3), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b'); plot(time,features(:,2),'m'); plot(time,features(:,3),'k'); plot(time,features(:,4),'g'); plot(time,features(:,5),'y'); axis tight; title(ada_string,'FontWeight','bold');
github
vitoruapt/lartkv5-master
train_net.m
.m
lartkv5-master/src/utils/process_target/matlab/train_net.m
907
utf_8
0d219bb6a1a146ccf798b6ec9b25b86f
%train neural network % function [net] = train_net(inputs,targets) function [net] = train_net(train_set,n_neurons) inputs = train_set(:,3:end); targets = train_set(:,2); targets(targets==0,2)=1; % Solve a Pattern Recognition Problem with a Neural Network inputs = inputs'; targets = targets'; % Create a Pattern Recognition Network hiddenLayerSize = n_neurons;%[10,10]; net = patternnet(hiddenLayerSize); %net.performParam.regularization = 0.1; % net.trainFcn = 'trainbr'; net.trainParam.max_fail = 100; % Setup Division of Data for Training, Validation, Testing %net.divideFcn = 'dividetrain' net.divideFcn = 'divideind'; net.divideParam.testInd = []; net.divideParam.trainInd = 1:8504; net.divideParam.valInd = 8505:10196; % net.divideparam.trainratio = 85/100; % net.divideparam.valratio = 10/100; % net.divideparam.testratio = 5/100; % Train the Network [net,tr] = train(net,inputs,targets);
github
vitoruapt/lartkv5-master
test_net.m
.m
lartkv5-master/src/utils/process_target/matlab/test_net.m
3,230
utf_8
8dc4a43efed1f2b19867805d622306f8
%test neural network function [] = test_net(net,test_set) for number = 1:length(test_set) test = test_set(number).set; name = test_set(number).name; %prepare the data features = test(:,3:end); input_val = features'; target_val = test(:,2)'; target_val(2,target_val == 0) = 1; gt_class = test(:,2); %second column has leader tag %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); % Test the Network outputs = net(input_val); %errors = gsubtract(y_val',outputs); %performance = perform(net,y_val',outputs) classes = round(outputs(2,:)); %classes = vec2ind(outputs) - 1; %%%%% debug plot %%%%%% % figure, hold; % plot(target_val','o'); % plot(outputs(1,:),'k'); % plot(outputs(2,:),'r'); % plot(classes,'y'); %diferences = abs(test_class - gd_class); % differences = abs(target_val(2,:)-classes); % error = length(find(differences == 1)); % error_ratio = error / length(differences); % title_string = ... % sprintf('NeuralNet Classification. error:%.2f',error_ratio); differences = classes - target_val(2,:); false_bad = length(find(differences == -1)); false_good = length(find(differences == 1)); false_total = false_bad + false_good; false_bad_ratio = false_bad / length(differences); false_good_ratio = false_good / length(differences); false_bad_ratio = round(false_bad_ratio*100)/100; false_good_ratio = round(false_good_ratio*100)/100; error_ratio = false_bad_ratio + false_good_ratio; title_string = ... sprintf('false good:%.2f, false bad:%.2f, total error:%.2f',... false_good_ratio, false_bad_ratio, error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% groundtruth plot %%%%%%%%%% bad_tag = test(gt_class == 1,1); % Show groundtruth figure; subplot(2,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); %axis equal; axis tight; title(['test:' name ' ' 'ground truth']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% classification plot %%%%%%% bad_tag = test(classes == 0,1); % Show classification subplot(2,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); plot(time,outputs(1,:),'bo'); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); %axis equal; axis tight; title(title_string); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end
github
vitoruapt/lartkv5-master
evaluate_model_single.m
.m
lartkv5-master/src/utils/process_target/matlab/evaluate_model_single.m
3,609
utf_8
b86fe2360a8aafd9d15d87f1c08468b1
%evaluates adaboost classifier, comparing groundtruth %with class output, may receive a single dataset or a structure of them, %create plots comparing ground truth and classification, also prints error %of false good, false bad and false total function [] = evaluate_model(model,test_set) if size(test_set,1)~=1 temp = test_set; clear test_set; test_set.set = temp; test_set.name = 'single'; end for number = 1:length(test_set) test = test_set(number).set; name = test_set(number).name; %prepare the data features = test(:,3:end); test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test(:,2); %second column has leader tag [-1 good / 1 bad] %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); tic % Classify the features with the trained model if(isstruct(model)) %classic adaboost test_class=adaboost('apply',features, model); else %matlab adaboost test_class=predict(model, features); end toc differences = test_class - gd_class; false_bad = length(find(differences == 2)); false_good = length(find(differences == -2)); false_total = false_bad + false_good; false_bad_ratio = false_bad / length(differences); false_good_ratio = false_good / length(differences); false_bad_ratio = round(false_bad_ratio*100)/100; false_good_ratio = round(false_good_ratio*100)/100; error_ratio = false_bad_ratio + false_good_ratio; title_string = ... sprintf('false good:%.2f, false bad:%.2f, total error:%.2f',... false_good_ratio, false_bad_ratio, error_ratio); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% target plot %%%%%%%%%%%%%%% bad_tag = test(gd_class == 1,1); % Show the data H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',2); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); subplot(2,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); axis tight; %axis equal title(['test:' name ' ' 'ground truth']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Show result bad_tag = test(test_class == 1,1); % Show the data subplot(2,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); axis tight; %axis equal; title(title_string); end end function large_markers tmp_l = legend('velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(tmp_l,'visible','off') xlabel('t(s)'); ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); %set(ax2,'position',get(ax1,'position')); hL = legend(ax2,'velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(ax2,'visible','off') axis(ax1, 'tight'); %set(gcf,'position',[200 200 800 400]); end
github
vitoruapt/lartkv5-master
train_adaboost.m
.m
lartkv5-master/src/utils/process_target/matlab/train_adaboost.m
5,522
utf_8
2362578a48eadb03855f3d3a151234ea
%trains an adaboost classifier, input is training set, and iterations are %the max number of weak classifiers allowed function [classestimate,model,feat_of_wc] = train_adaboost(data,iterations) %train adaboost classifier downloaded from internet %features: % 3: target velocity % 4: lateral displacement (former relative velocity) % 5: heading difference % 6: angle between robot head and target pos % 7: distance % 8: relative velocity x % 9: relative velocity y datafeatures = data(:,3:end); % data classification data(data(:,2)==0,2)=-1; %transform from 0 to -1 dataclass = data(:,2); %second column has leader tag % Use Adaboost to make a classifier [classestimate,model]=adaboost('train',datafeatures,dataclass,iterations); % Show the error verus number of weak classifiers error=zeros(1,length(model)); feat_of_wc = zeros(1,length(model)); cont_ratio = zeros(1,size(datafeatures,2)); for i=1:length(model) error(i)=model(i).error; feature_id = model(i).dimension; feat_of_wc(i) = feature_id; cont_ratio(feature_id)=cont_ratio(feature_id)+model(i).alpha; end cont_ratio = cont_ratio./sum(cont_ratio); fh1 = figure; set(fh1,'defaultlinelinewidth',3); set(fh1,'defaultaxeslinewidth',2); set(fh1,'defaulttextfontsize',12); set(fh1,'defaultaxesfontsize',12); set(fh1,'position',[480 210 800 400]); hold, title('Classification error versus number of weak classifiers'); plot(error); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fh2 = figure; set(fh2,'defaultlinelinewidth',3); set(fh2,'defaultaxeslinewidth',2); set(fh2,'defaulttextfontsize',12); set(fh2,'defaultaxesfontsize',12); set(fh2,'position',[ 679 106 600 400]); hold, title('Features'); % [H,X] = hist(feat_of_wc,1:size(datafeatures,2)); [H,X] = hist(feat_of_wc,1:size(datafeatures,2)); a = [H;X]'; a(:,3) = a(:,1)/length(feat_of_wc); sortrows(a) cm = jet(length(X)); for i=1:length(X) h=bar(X(i),H(i)); set(h,'facecolor',cm(i,:)); end ylabel('weak classifiers'); set(gca,'XTickLabel',[]); axis tight; % legend('velocity',... % 'lateral displacement',... % 'relative heading',... % 'angle','distance',... % 'relative vel. x',... % 'relative vel. y',... % 'location','eastOutside'); legend('mean target vel.',... 'mean lat. displ.',... 'mean rel. head.',... 'mean angle',... 'mean distance',... 'mean relative vel. x',... 'mean relative vel. y',... 'Location','eastOutside') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fh3 = figure; set(fh3,'defaultlinelinewidth',3); set(fh3,'defaultaxeslinewidth',2); set(fh3,'defaulttextfontsize',12); set(fh3,'defaultaxesfontsize',12); set(fh3,'position',[ 679 106 600 400]); hold, title({'Features Contribution Ratio';... sprintf('(number of weak classifiers = %i)',length(feat_of_wc))}) %X = 1:length(cont_ratio); H = cont_ratio; cm = jet(length(X)); for i=1:length(X) h2=bar(X(i),H(i)); set(h2,'facecolor',cm(i,:)); end ylabel('contribution ratio'); set(gca,'XTick',1:21); set(gcf,'position',[250 100 1200 500]); axis tight; set(gca,'YLim',[0 0.25]); grid; legend('1. lateral displ.',... '2. rel. heading',... '3. angle',... '4. distance',... '5. stdv distance',... 'Location','eastOutside'); legend('1. target velocity',... '2. lateral displ.',... '3. rel. heading',... '4. angle',... '5. distance',... '6. relative vel. x',... '7. relative vel. y',... '8. stdv target vel.',... '9. stdv lateral displ.',... '10. stdv rel. head.',... '11. stdv angle',... '12. stdv distance',... '13. stdv relative vel. x',... 'Location','eastOutside'); % if (length(H)~=length(X)) % X = [1 round(X)] % end a = [H;X]'; sortrows(a) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % legend('1. target velocity',... % '2. lateral displ.',... % '3. rel. heading',... % '4. angle',... % '5. distance',... % '6. relative vel. x',... % '7. relative vel. y',... % '8. \Delta target vel.',... % '9. \Delta lateral displ.',... % '10. \Delta rel. head.',... % '11. \Delta angle',... % '12. \Delta distance',... % '13. \Delta relative vel. x',... % '14. \Delta relative vel. y',... % '15. stdv target vel.',... % '16. stdv lateral displ.',... % '17. stdv rel. head.',... % '18. stdv angle',... % '19. stdv distance',... % '20. stdv relative vel. x',... % '21. stdv relative vel. y',... % 'Location','eastOutside'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Training results % Show results % blue=datafeatures(classestimate==-1,:); red=datafeatures(classestimate==1,:); % I=zeros(161,161); % for i=1:length(model) % if(model(i).dimension==1) % if(model(i).direction==1), rec=[-80 -80 80+model(i).threshold 160]; % else rec=[model(i).threshold -80 80-model(i).threshold 160 ]; % end % else % if(model(i).direction==1), rec=[-80 -80 160 80+model(i).threshold]; % else rec=[-80 model(i).threshold 160 80-model(i).threshold]; % end % end % rec=round(rec); % y=rec(1)+81:rec(1)+81+rec(3); x=rec(2)+81:rec(2)+81+rec(4); % I=I-model(i).alpha; I(x,y)=I(x,y)+2*model(i).alpha; % end % subplot(2,2,2), imshow(I,[]); colorbar; axis xy; % colormap('jet'), hold on % plot(blue(:,1)+81,blue(:,2)+81,'bo'); % plot(red(:,1)+81,red(:,2)+81,'ro'); % title('Training Data classified with adaboost model');
github
vitoruapt/lartkv5-master
leader_features.m
.m
lartkv5-master/src/utils/process_target/matlab/leader_features.m
4,394
utf_8
c2c7a6b0afe6ec5c38886b61eda5b343
%extract features from chosen target and %stores it in a matlab variable (proc_target) %must pass as arguments the name of the file, generated by ROS %log file from process_target, and the id of the desired subject %function [robot,proc_target]=leader_features(file,target_id) function [proc_target]=leader_features(file,target_id) % input file format: % 1: id % 2: good/bad tag % 3: time % 4: pos x % 5: pos y % 6: vel % 7: theta % 8: pos diff % 9: head diff %10: angle 2 robot %11: velocity diff %printf("%d,%d,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f\n", % target_id, badLeader, time_elapsed.toSec(), % target_x, target_y, target_vel, target_theta, % position_diff, heading_diff, angle_to_robot, velocity_diff); % output file format: % 1: time % 2: good/bad tag % 3: mean vel 1 % 4: mean vel diff 2 % 5: mean head diff 3 % 6: angle 2 robot 4 % 7: mean dist 2 robot 5 %initialize vars begin_sweep = 1; end_sweep = 1; counter = 1; mean_fig = figure; hold on; grid on; %load and rearrange targets file list = load(file); range = max(list(:,1)) + 2; cm = jet(range); figure,hold; %axis square; for i = 1:length(list); if(list(i,1)==-1) plot3(list(i,4),list(i,5),list(i,3),'bo'); % plot3(list(i,4),list(i,5),list(i,3),'o','color',cm((list(i,1)+2),:)); elseif(list(i,1)==target_id) plot3(list(i,4),list(i,5),list(i,3),'ro'); end end %axis equal; list = sortrows(list); % separate target from robot while counter < length(list) while list(begin_sweep,1) == list(end_sweep,1) end_sweep = end_sweep + 1; counter = counter + 1; if counter > length(list) break end end %only pick one target, according to input of function switch list(begin_sweep,1) case -1 robot = list(begin_sweep:end_sweep-1,:); case target_id target = list(begin_sweep:end_sweep-1,:); end begin_sweep = end_sweep; end % filter data proc_target(length(target),7) = 0; proc_target(:,1) = target(:,3); proc_target(:,2) = target(:,2); proc_target(:,6) = target(:,10); %angle 2 robot proc_target(:,3) = target(:,6); %vel proc_target(:,4) = target(:,11); %vel diff proc_target(:,5) = target(:,9); %head diff proc_target(:,6) = target(:,10); %angle 2 robot proc_target(:,7) = target(:,8); %pos diff (dist) % for i=1:length(target) % winsize = 50; % while(i-winsize <= 0) %not enough past info % winsize = winsize - 1; % end % proc_target(i,3) = mean(target(i-winsize:i,6)); %vel % proc_target(i,4) = mean(target(i-winsize:i,11)); %vel diff % proc_target(i,5) = mean(target(i-winsize:i,9)); %head diff % %proc_target(i,6) = mean(target(i-winsize:i,10)); %angle 2 robot % proc_target(i,7) = mean(target(i-winsize:i,8)); %pos diff (dist) % end %%%%%%%%% PLOTTING %%%%%%%%%%%% %removing angle jump % robot(:,7) = unwrap(robot(:,7)); % robot(:,9) = unwrap(robot(:,9)); % robot(:,10) = unwrap(robot(:,10)); % target(:,7) = unwrap(target(:,7)); % target(:,9) = unwrap(target(:,9)); % target(:,10) = unwrap(target(:,10)); %proc_target(:,5) = unwrap(proc_target(:,5)); %proc_target(:,6) = unwrap(proc_target(:,6)); % if(max(proc_target(:,5)>pi)) % proc_target(:,5) = proc_target(:,5) - 2*pi; % elseif(min(proc_target(:,5)<-pi)) % proc_target(:,5) = proc_target(:,5) + 2*pi; % end %plot good/bad leader index tag = find(diff(proc_target(:,2))); figure(mean_fig); plot(proc_target(:,1),proc_target(:,3),'b-'); plot(proc_target(:,1),proc_target(:,4),'r-'); plot(proc_target(:,1),proc_target(:,5),'k-'); plot(proc_target(:,1),proc_target(:,6),'g-'); plot(proc_target(:,1),proc_target(:,7),'y-'); legend('vel','vel diff','head diff','angle', 'distance',... 'Location','NorthWest'); title('mean features from target 2 robot'); if ~isempty(tag) line([proc_target(tag,1) proc_target(tag,1)],[0 5]) %plot(proc_target(tag,1),0:0.1:5); end %proc_target = crop_features(proc_target); figure(mean_fig); plot(proc_target(:,1),proc_target(:,3),'bo'); plot(proc_target(:,1),proc_target(:,4),'ro'); plot(proc_target(:,1),proc_target(:,5),'ko'); plot(proc_target(:,1),proc_target(:,6),'go'); plot(proc_target(:,1),proc_target(:,7),'yo'); legend('vel','vel diff','head diff','angle', 'distance',... 'Location','NorthWest');
github
vitoruapt/lartkv5-master
plot_labels.m
.m
lartkv5-master/src/utils/process_target/matlab/plot_labels.m
4,314
utf_8
ebee9d9693bb54f2e92624c850c4223d
%compare the labels created by the three evaluators with, also plotting the %final tag, for illustrative purposes only. function [] = plot_labels(test,final_tag) features = test(:,5:end); low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); % Create figure F = figure('position',[360 260 900 600]); set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',1.5); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); %%%%%%%%%%% pro plot %%%%%%%%%% gd_class = test(:,2); bad_tag = test(gd_class == 1,1); H = subplot(3,1,1,'position',[0.065 0.70 0.70 0.20]); hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]); %axis equal; axis tight; ax_x = get(H, 'xlim'); ax_y = get(H, 'ylim'); box on; set(gca,'XTickLabel',[]); %set(gca,'YTickLabel',[]); ylabel('pro'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% rich plot %%%%%%%%%% gd_class = test(:,3); %rich tag bad_tag = test(gd_class == 1,1); % Show the data I = subplot(3,1,2,'position',[0.065 0.4125 0.70 0.20]); hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]); %axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); set(gca,'XTickLabel',[]); box on; %set(gca,'YTickLabel',[]); ylabel('rich'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% jor plot %%%%%%%%%% gd_class = test(:,4); %jorge_tag bad_tag = test(gd_class == 1,1); % Show the data I = subplot(3,1,3,'position',[0.065 0.1250 0.70 0.20]); hold on, grid on; if ~isempty(bad_tag) left = bad_tag(1); right = bad_tag(end); top = up_plot; bottom = low_plot; patch([left left right right],... [bottom top top bottom],... [0.7 0.7 0.7],... 'FaceAlpha',0.5); line([final_tag final_tag],... [bottom top],... 'color',[1 0 0]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'.','color',[0.7 0 0]);%axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); box on; xlabel('t(s)'); %set(gca,'YTickLabel',[]); ylabel('jor'); large_markers %%%%%%%%%%%%%%%%%%%%%%%%%%% p_tag = test(diff(test(:,2))==1,1); r_tag = test(diff(test(:,3))==1,1); j_tag = test(diff(test(:,4))==1,1); [p_tag r_tag j_tag] %%%%%%%%%%%%%%%%%%%%%%%% end function large_markers xlabel('t(s)'); ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); plot(0,0,'color',[0.7 0.7 0.7],'linewidth',10,'parent',ax2); % hL = legend(ax2,'velocity','rel velocity',... % 'rel heading','angle','distance','bad leader region',... % 'final tag',... % 'location','eastOutside'); hL = legend(ax2,'velocity (m/s)','lateral disp. (m)',... 'relative head. (rad)','angle (rad)','distance (m)',... 'relative vel. x (m/s)','relative vel. y (m/s)','cropped region',... 'location','eastOutside'); set(hL,'position', [0.80 0.35 0.15 0.30]); set(ax2,'visible','off') axis(ax1, 'tight'); end
github
vitoruapt/lartkv5-master
plot_test2.m
.m
lartkv5-master/src/utils/process_target/matlab/plot_test2.m
2,313
utf_8
968d8618023c1cc38d47190720487c42
%used in do_tag to show comparison between labels function [] = plot_test2(test_a) features = test_a(:,5:end); %test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test_a(:,2); %second column has leader tag low_plot = min(min(features)); up_plot = max(max(features)); time = test_a(:,1); bad_tag = test_a(gd_class == 1,1); % Show the data F = figure; set(F,'defaultlinelinewidth',3); set(F,'defaultaxeslinewidth',2); set(F,'defaulttextfontsize',12); set(F,'defaultaxesfontsize',12); H = subplot(3,1,1); hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[0.5 0.5 0.5]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); %axis equal; axis tight; ax_x = get(H, 'xlim'); ax_y = get(H, 'ylim'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% features = test_a(:,5:end); %test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test_a(:,3); %rich tag low_plot = min(min(features)); up_plot = max(max(features)); time = test_a(:,1); bad_tag = test_a(gd_class == 1,1); % Show the data I = subplot(3,1,2); hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[0.5 0.5 0.5]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); %axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% features = test_a(:,5:end); %test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test_a(:,4); %jorge_tag low_plot = min(min(features)); up_plot = max(max(features)); time = test_a(:,1); bad_tag = test_a(gd_class == 1,1); % Show the data I = subplot(3,1,3); hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[0.5 0.5 0.5]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'m.'); plot(time,features(:,3),'k.'); plot(time,features(:,4),'g.'); plot(time,features(:,5),'y.'); %axis equal; axis tight; set(I,'xlim',ax_x); set(I,'ylim',ax_y); xlabel('t(s)'); %%%%%%%%%%%%%%%%%%%%%%%%%%% p_tag = test_a(diff(test_a(:,2))==1,1); r_tag = test_a(diff(test_a(:,3))==1,1); j_tag = test_a(diff(test_a(:,4))==1,1); [p_tag r_tag j_tag]
github
vitoruapt/lartkv5-master
enhance_features.m
.m
lartkv5-master/src/utils/process_target/matlab/enhance_features.m
4,253
utf_8
891a77b7a8827b581b59f2bf33af6c4e
%compute new features based on existing ones % % derivatives from position 10 to 16 % standard deviation, based on winsize, position 17 to 23 % mean, based on winsize, position 24 to 30 % % in final part, must uncomment the desired set, using only portions of % the features computed, eliminating features with reduced contribution % for example % % % 3 velocity % 4 lateral displacement % 5 relative heading % 6 angle 2 robot % 7 distance % 8 relative velocity x % 9 relative velocity y function new_features = enhance_features(input_features) new_features = input_features; % diff part new_features(2:end,10) = diff(input_features(:,3)); new_features(2:end,11) = diff(input_features(:,4)); new_features(2:end,12) = diff(input_features(:,5)); new_features(2:end,13) = diff(input_features(:,6)); new_features(2:end,14) = diff(input_features(:,7)); new_features(2:end,15) = diff(input_features(:,8)); new_features(2:end,16) = diff(input_features(:,9)); new_features(1,10) = new_features(2,10); new_features(1,11) = new_features(2,11); new_features(1,12) = new_features(2,12); new_features(1,13) = new_features(2,13); new_features(1,14) = new_features(2,14); new_features(1,15) = new_features(2,15); new_features(1,16) = new_features(2,16); % mean and stdv part for i = 1:length(input_features) winsize = 30; while(i-winsize <= 0) %not enough past info winsize = winsize - 1; end % stdv part new_features(i,17) = std(input_features(i-winsize:i,3)); %std vel new_features(i,18) = std(input_features(i-winsize:i,4)); %std lat. disp. new_features(i,19) = std(input_features(i-winsize:i,5)); %std rel. head. new_features(i,20) = std(input_features(i-winsize:i,6)); %std angle 2 robot new_features(i,21) = std(input_features(i-winsize:i,7)); %std dist new_features(i,22) = std(input_features(i-winsize:i,8)); %std rel v x new_features(i,23) = std(input_features(i-winsize:i,8)); %std rel v y % mean part new_features(i,24) = mean(input_features(i-winsize:i,3)); %mean vel new_features(i,25) = mean(input_features(i-winsize:i,4)); %mean lat. disp. new_features(i,26) = mean(input_features(i-winsize:i,5)); %mean rel. head new_features(i,27) = mean(input_features(i-winsize:i,6)); %mean angle 2 robot new_features(i,28) = mean(input_features(i-winsize:i,7)); %mean dist new_features(i,29) = mean(input_features(i-winsize:i,8)); %mean rel v x new_features(i,30) = mean(input_features(i-winsize:i,9)); %mean rel v y end % %test single feature thresholds % new_features = [new_features(:,1:2)... % new_features(:,7)]; %test integration with opencv adaboost % new_features = [new_features(:,1:2)... % new_features(:,3:7)]; % %test vel, lat dist., dist % new_features = [new_features(:,1:2)... % new_features(:,3)... % new_features(:,4)... % new_features(:,7)... % ]; % %reduced4 (lat. displ., dist., stdv distance) % new_features = [new_features(:,1:2)... % new_features(:,4)... % new_features(:,7)... % new_features(:,21)... % ]; % %reduced3 ODNM (minus relvx, relvy, stdv ld, stdv dist) % new_features = [new_features(:,1:2)... % new_features(:,3:7)... % ]; % %reduced3 (lat. displ., rel. heading, angle, dist. stdv distance) % new_features = [new_features(:,1:2)... % new_features(:,4:7)... % new_features(:,21)... % ]; %reduced2 == ODNM % new_features = [new_features(:,1:2)... % new_features(:,3:9)... % new_features(:,17)... % new_features(:,21)... % ]; % %reduced1 (no diff, no stdv rel_v_y) % new_features = [new_features(:,1:2)... % new_features(:,3:9)... % new_features(:,17:22)... % ]; % %train complete new_features = [new_features(:,1:2)... new_features(:,3:9)... new_features(:,10:16)... new_features(:,17:23)... ]; % %train no diff % new_features = [new_features(:,1:2)... % new_features(:,3:9)... % new_features(:,17:23)... % ]; %with mean % new_features = [new_features(:,1:2)... % new_features(:,3:9)... %kf output % new_features(:,10:16)... %diff % new_features(:,17:23)... %stdv % new_features(:,24:30)... %mean % ]; %only one % new_features = [new_features(:,1:2)... % new_features(:,3)];
github
vitoruapt/lartkv5-master
new_features.m
.m
lartkv5-master/src/utils/process_target/matlab/new_features.m
263
utf_8
64fbb408c530fb0bd97e9027cb513024
%decompose relative velocity in x and y, compute lateral displacement function [out]=new_features(in) out = in; [rel_vel_x rel_vel_y] = relative_velocities(in); out(:,8) = rel_vel_x; out(:,9) = rel_vel_y; out(:,4) = sin(in(:,6)).*in(:,7); %put ld in place of rv
github
vitoruapt/lartkv5-master
crop_features.m
.m
lartkv5-master/src/utils/process_target/matlab/crop_features.m
1,981
utf_8
a3fc318bef5c147ab0e5fb5c62756f4f
%crop variable containing leader features %so transitory measurments from beginning and %end can be removed %inputs: %in_data : input data %x1: inferior crop limit %x2: superior crop limit function [out_data] = crop_features(in_data,x1,x2) % Show the data H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',1.5); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); hold on, grid on; title('Cropped Fatures'); set(gcf,'position',[200 200 800 300]); [val1 ind1] = min(abs(in_data(:,1)-x1)); [val2 ind2] = min(abs(in_data(:,1)-x2)); top = max(max(in_data(:,3:9))); bottom = min(min(in_data(:,3:9))); patch([x1 x1 x2 x2],... [bottom top top bottom],... [0.7 0.7 0.7]);%,'faceAlpha',0.5); plot(in_data(:,1),in_data(:,3),'bo'); plot(in_data(:,1),in_data(:,4),'co'); plot(in_data(:,1),in_data(:,5),'ko'); plot(in_data(:,1),in_data(:,6),'go'); plot(in_data(:,1),in_data(:,7),'yo'); plot(in_data(:,1),in_data(:,8),'mo'); plot(in_data(:,1),in_data(:,9),'o','color',[0.5 0 0]); legend('vel','vel diff','head diff','angle', 'dist diff',... 'Location','eastOutside'); xlabel('t(s)'); axis tight; out_data = in_data(ind1:ind2,:); %large markers ax1 = gca; ax2 = axes('position',get(ax1,'position')); hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); plot(0,0,'color',[0.7 0.7 0.7],'linewidth',10,'parent',ax2); %set(ax2,'position',get(ax1,'position')); HL = legend(ax2,'velocity (m/s)','lateral disp. (m)',... 'relative head. (rad)','angle (rad)','distance (m)',... 'relative vel. x (m/s)','relative vel. y (m/s)','cropped region',... 'location','eastOutside'); set(HL,'position',[0.7650 0.35 0.23 0.37]); set(ax2,'visible','off') %axis(ax1, 'tight');
github
vitoruapt/lartkv5-master
evaluate_model.m
.m
lartkv5-master/src/utils/process_target/matlab/evaluate_model.m
5,501
utf_8
ecf0d85ca58f00874687aa0be33c94df
%evaluates adaboost classifier, comparing groundtruth %with class output, may receive a single dataset or a structure of them, %create plots comparing ground truth and classification, also prints error %of false good, false bad and false total function [] = evaluate_model(model,test_set) if size(test_set,1)~=1 temp = test_set; clear test_set; test_set.set = temp; test_set.name = 'single'; end for number = 1:length(test_set) test = test_set(number).set; name = test_set(number).name; %prepare the data features = test(:,3:end); test(test(:,2)==0,2)=-1; %transform from 0 to -1 gd_class = test(:,2); %second column has leader tag [-1 good / 1 bad] %for plot purposes low_plot = min(min(features)); up_plot = max(max(features)); time = test(:,1); tic % Classify the features with the trained model if(isstruct(model)) %classic adaboost test_class=adaboost('apply',features, model); else %matlab adaboost test_class=predict(model, features); end toc differences = test_class - gd_class; false_bad = length(find(differences == 2)); false_good = length(find(differences == -2)); false_total = false_bad + false_good; false_bad_ratio = false_bad / length(differences); false_good_ratio = false_good / length(differences); % error_ratio = false_total / length(differences); false_bad_ratio = round(false_bad_ratio*100)/100; false_good_ratio = round(false_good_ratio*100)/100; error_ratio = false_bad_ratio + false_good_ratio; % error_ratio = round(error_ratio*100)/100; title_string = ... sprintf('false good:%.2f, false bad:%.2f, total error:%.2f',... false_good_ratio, false_bad_ratio, error_ratio); %title_string = ['test:' name ' ' title_string]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% target plot %%%%%%%%%%%%%%% bad_tag = test(gd_class == 1,1); % Show the data H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',2); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); subplot(2,1,1), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'color',[0.5 0 0]); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); axis tight; %axis equal title(['test:' name ' ' 'ground truth']); % large_markers; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Show result bad_tag = test(test_class == 1,1); % Show the data subplot(2,1,2), hold on, grid on; if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end plot(time,features(:,1),'b.'); plot(time,features(:,2),'c.'); plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); % plot(time,features(:,6),'m.'); % plot(time,features(:,7),'color',[0.5 0 0]); %legend('vel','vel diff','head diff','angle', 'distance',... % 'Location','NorthWest'); axis tight; %axis equal; title(title_string); % large_markers; end %set(gcf,'position',[200 200 800 400]); score(length(test_class)-1)=0; for i=1:length(test_class) if test_class(i)==-1 vote = 0.01; else vote = -0.5; end score(i+1) = score(i) + vote; if score(i+1) > 1 score(i+1) = 1; elseif score(i+1) < -0.1 score(i+1) = -0.1; end end X = figure; hold; set(X,'position',[200 400 800 300]); set(X,'defaultlinelinewidth',3); set(X,'defaultaxeslinewidth',2); set(X,'defaulttextfontsize',12); set(X,'defaultaxesfontsize',12); line([bad_tag bad_tag],[-0.1 1],'Color',[1 0 0.1]); score = score(1:end-1); sc = plot(time,score); l1 = line([time(1) time(end)],[0 0],'Color',[1 0 0.1]); l2 = line([time(1) time(end)],[0 0],'Color',[0 0 0]); legend([l1, sc, l2],'bad leader','leader score','threshold',... 'location','eastoutside'); axis tight; xlabel('time (s)'), ylabel('score'); end function large_markers tmp_l = legend('velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(tmp_l,'visible','off') xlabel('t(s)'); ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); %set(ax2,'position',get(ax1,'position')); hL = legend(ax2,'velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(ax2,'visible','off') axis(ax1, 'tight'); %set(gcf,'position',[200 200 800 400]); end
github
vitoruapt/lartkv5-master
ros_interface.m
.m
lartkv5-master/src/utils/process_target/matlab/old/ros_interface.m
1,701
utf_8
84fa1bd62878c2e5189bebed40138987
%interface with ros, receives a feature message and %apply classifier, then outputs a new message with %the classification function []=ros_subscriber(model) % create a publisher for a geometry_msgs/Pose message pub_process = geometry_msgs_Pose(... 'connect','publisher','subscribe_to_matlab','pose'); % create a subscriber for a geometry_msgs/Twist message sub_process = geometry_msgs_PoseWithCovariance(... 'connect','subscriber','publish_to_matlab','PoseWithCovariance'); % create an empty messages structure out_msg = geometry_msgs_Pose('empty'); in_msg = geometry_msgs_PoseWithCovariance('empty'); % read a message and print to screen while (1) in_msg = geometry_msgs_PoseWithCovariance('read', sub_process, 100); if ~isempty(in_msg) tic %info is being passed in the covariance struct x_pos = in_msg.pose.position.x; y_pos = in_msg.pose.position.y; id = in_msg.pose.position.z; sample = [in_msg.covariance(1) ... in_msg.covariance(2) ... in_msg.covariance(3) ... in_msg.covariance(4) ... in_msg.covariance(5)]; if(isstruct(model)) %to be used with classic adaboost %quality = ada_classify(sample,model); quality = adaboost('apply', sample, model); else %to be used with adaboost from matlab quality = predict(model,sample); end out_msg.position.x = x_pos; out_msg.position.y = y_pos; out_msg.position.z = quality; out_msg.orientation.x = id; geometry_msgs_Pose('send', pub_process, out_msg); toc end end
github
vitoruapt/lartkv5-master
plot_test.m
.m
lartkv5-master/src/utils/process_target/matlab/old/plot_test.m
2,514
utf_8
4802dbf48aec6bab59fcfc490193758f
%compares pro tag before and after shift, function [] = plot_test(test_set) features = test_set(:,3:end); good_tag = test_set(:,2); %second column has leader tag bad_tag = test_set(good_tag == 1,1); low_plot = min(min(features)); up_plot = max(max(features)); time = test_set(:,1); % Show the data H = figure; set(H,'defaultlinelinewidth',3); set(H,'defaultaxeslinewidth',2); set(H,'defaulttextfontsize',12); set(H,'defaultaxesfontsize',12); hold on, grid on; title('Features over time'); if ~isempty(bad_tag) line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); end v = plot(time,features(:,1),'b.'); %velocity ld = plot(time,features(:,2),'c.'); %lateral displacement rh = plot(time,features(:,3),'k.'); %heading diff a = plot(time,features(:,4),'g.'); %angle to robot d = plot(time,features(:,5),'y.'); %distance rv_x = plot(time,-features(:,6),'m.'); %relative velocity x rv_y = plot(time,features(:,7),'color',[0.5 0 0]); %relative velocity y legend([v,ld,rh,a,d,rv_x,rv_y],'velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); xlabel('t(s)'); %large markers ax1 = gca; ax2 = axes; hold; plot(0,0,'b','linewidth',10,'parent',ax2); plot(0,0,'c','linewidth',10,'parent',ax2); plot(0,0,'k','linewidth',10,'parent',ax2); plot(0,0,'g','linewidth',10,'parent',ax2); plot(0,0,'y','linewidth',10,'parent',ax2); plot(0,0,'m','linewidth',10,'parent',ax2); plot(0,0,'color',[0.5 0 0],'linewidth',10,'parent',ax2); %set(ax2,'position',get(ax1,'position')); legend(ax2,'velocity','lateral displacement',... 'relative heading','angle','distance',... 'relative vel. x','relative vel. y',... 'location','eastOutside'); set(ax2,'visible','off') axis(ax1, 'tight'); set(gcf,'position',[200 200 800 400]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % features = test_b(:,5:end); % %test(test(:,2)==0,2)=-1; %transform from 0 to -1 % gd_class = test_b(:,2); %rich tag % low_plot = min(min(features)); % up_plot = max(max(features)); % time = test_b(:,1); % % bad_tag = test_b(gd_class == 1,1); % % % Show the data % I = subplot(2,1,2); hold on, grid on; % if ~isempty(bad_tag) % line([bad_tag bad_tag],[low_plot up_plot],'Color',[1 0 0.1]); % end % plot(time,features(:,1),'b.'); % plot(time,features(:,2),'m.'); % plot(time,features(:,3),'k.'); % plot(time,features(:,4),'g.'); % plot(time,features(:,5),'y.'); % %axis equal; % axis tight; % %set(I,'xlim',ax_x); % set(I,'ylim',ax_y);
github
vitoruapt/lartkv5-master
test_ensemble.m
.m
lartkv5-master/src/utils/process_target/matlab/old/test_ensemble.m
219
utf_8
2057f682ef3cecaa6ab5d76aa489ef52
%test different 4 situations with classifier function [] = test_ensemble(model,stopped,good,aside,far) evaluate_model(model,stopped); evaluate_model(model,good); evaluate_model(model,aside); evaluate_model(model,far);
github
vitoruapt/lartkv5-master
ros_ann.m
.m
lartkv5-master/src/utils/process_target/matlab/old/ros_ann.m
1,651
utf_8
87dfddc5f632bdf0e31bf7bf52a2a6bc
%interface with ros, receives a feature message and %apply classifier, then outputs a new message with %the classification function []=ros_subscriber(model) % create a publisher for a geometry_msgs/Pose message pub_process = geometry_msgs_Pose(... 'connect','publisher','subscribe_to_matlab','pose'); % create a subscriber for a geometry_msgs/Twist message sub_process = geometry_msgs_PoseWithCovariance(... 'connect','subscriber','publish_to_matlab','PoseWithCovariance'); % create an empty messages structure out_msg = geometry_msgs_Pose('empty'); in_msg = geometry_msgs_PoseWithCovariance('empty'); % read a message and print to screen while (1) in_msg = geometry_msgs_PoseWithCovariance('read', sub_process, 100); if ~isempty(in_msg) %info is being passed in the covariance struct x_pos = in_msg.pose.position.x; y_pos = in_msg.pose.position.y; id = in_msg.pose.position.z; sample = [in_msg.covariance(1) ... in_msg.covariance(2) ... in_msg.covariance(3) ... in_msg.covariance(4) ... in_msg.covariance(5)]; quality = model(sample'); %round to 1 or 0 quality = round(quality(2,:)); %ros expects -1 good / 1 bad switch quality case 1 quality = -1; case 0 quality = 1; end out_msg.position.x = x_pos; out_msg.position.y = y_pos; out_msg.position.z = quality; out_msg.orientation.x = id; geometry_msgs_Pose('send', pub_process, out_msg); end end
github
vitoruapt/lartkv5-master
do_transition.m
.m
lartkv5-master/src/utils/process_target/matlab/old/do_transition.m
245
utf_8
9c9e7c379455091aff623a8171bc64f3
%back tagging, never used function out = do_transition(in) out = in; tag_i = find(diff(in(:,2))==1); timestep = mean(diff(in(:,1))); window = 1; steps = round(window/timestep); trans_i = tag_i - steps; out(:,2)=0; out(trans_i:tag_i,2)=1; end
github
vitoruapt/lartkv5-master
pdftops.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/pdftops.m
3,077
utf_8
8dff856e4b450072050d8aa571d1a08e
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops. % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path % under linux. % 23/01/2014 - Add full path to pdftops.txt in warning. % Call pdftops [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); end function path_ = xpdf_path % Return a valid path % Start with the currently set path path_ = user_string('pdftops'); % Check the path works if check_xpdf_path(path_) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path_ = bin; return end % Search the obvious places if ispc path_ = 'C:\Program Files\xpdf\pdftops.exe'; else path_ = '/usr/local/bin/pdftops'; end if check_store_xpdf_path(path_) return end % Ask the user to enter the path while 1 if strncmp(computer,'MAC',3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.')) end base = uigetdir('/', 'Pdftops not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path_ = [base bin_dir{a} bin]; if exist(path_, 'file') == 2 break; end end if check_store_xpdf_path(path_) return end end error('pdftops executable not found.'); end function good = check_store_xpdf_path(path_) % Check the path is valid good = check_xpdf_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path_) warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt')); return end end function good = check_xpdf_path(path_) % Check the path is valid [good, message] = system(sprintf('"%s" -h', path_)); % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); end
github
vitoruapt/lartkv5-master
crop_borders.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/crop_borders.m
1,669
utf_8
725f526e7270a9b417300035d8748a9c
%CROP_BORDERS Crop the borders of an image or stack of images % % [B, v] = crop_borders(A, bcol, [padding]) % %IN: % A - HxWxCxN stack of images. % bcol - Cx1 background colour vector. % padding - scalar indicating how many pixels padding to have. Default: 0. % %OUT: % B - JxKxCxN cropped stack of images. % v - 1x4 vector of start and end indices for first two dimensions, s.t. % B = A(v(1):v(2),v(3):v(4),:,:). function [A, v] = crop_borders(A, bcol, padding) if nargin < 3 padding = 0; end [h, w, c, n] = size(A); if isscalar(bcol) bcol = bcol(ones(c, 1)); end bail = false; for l = 1:w for a = 1:c if ~all(col(A(:,l,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end bcol = A(ceil(end/2),w,:,1); bail = false; for r = w:-1:l for a = 1:c if ~all(col(A(:,r,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end bcol = A(1,ceil(end/2),:,1); bail = false; for t = 1:h for a = 1:c if ~all(col(A(t,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end bcol = A(h,ceil(end/2),:,1); bail = false; for b = h:-1:t for a = 1:c if ~all(col(A(b,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop the background, leaving one boundary pixel to avoid bleeding on resize v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)]; A = A(v(1):v(2),v(3):v(4),:,:); end function A = col(A) A = A(:); end
github
vitoruapt/lartkv5-master
isolate_axes.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/isolate_axes.m
3,668
utf_8
e2dce471e433886fcb87f9dcb284a2cb
%ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes/uipanels % specified, and also their associated legends and colorbars. The objects % specified must all be in the same figure, but they will generally only be % a subset of the objects in the figure. % % IN: % ah - An array of axes and uipanel handles, which must come from the % same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2013 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m. % 12/12/12 - Add support for isolating uipanels. Thanks to michael for % suggesting it. % 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!). % 05/12/13 - Bug fix to axes having different units. Thanks to Remington % Reid for reporting the issue. function fh = isolate_axes(ah, vis) % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes or uipanels, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) error('All handles must be axes or uipanel handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the objects so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the object tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of objects found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'}); nLeg = numel(lh); if nLeg > 0 set([ah(:); lh(:)], 'Units', 'normalized'); ax_pos = get(ah, 'OuterPosition'); if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); leg_pos = get(lh, 'OuterPosition'); if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); ax_pos = shiftdim(ax_pos, -1); % Overlap test M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ... bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ... bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ... bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2)); ah = [ah; lh(any(M, 2))]; end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input objects and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); end function ah = allchildren(ah) ah = findall(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); end function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end end
github
vitoruapt/lartkv5-master
im2gif.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/im2gif.m
6,048
utf_8
5a7437140f8d013158a195de1e372737
%IM2GIF Convert a multiframe image to an animated GIF file % % Examples: % im2gif infile % im2gif infile outfile % im2gif(A, outfile) % im2gif(..., '-nocrop') % im2gif(..., '-nodither') % im2gif(..., '-ncolors', n) % im2gif(..., '-loops', n) % im2gif(..., '-delay', n) % % This function converts a multiframe image to an animated GIF. % % To create an animation from a series of figures, export to a multiframe % TIFF file using export_fig, then convert to a GIF, as follows: % % for a = 2 .^ (3:6) % peaks(a); % export_fig test.tif -nocrop -append % end % im2gif('test.tif', '-delay', 0.5); % %IN: % infile - string containing the name of the input image. % outfile - string containing the name of the output image (must have the % .gif extension). Default: infile, with .gif extension. % A - HxWxCxN array of input images, stacked along fourth dimension, to % be converted to gif. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -nodither - option indicating that dithering is not to be used when % converting the image. % -ncolors - option pair, the value of which indicates the maximum number % of colors the GIF can have. This can also be a quantization % tolerance, between 0 and 1. Default/maximum: 256. % -loops - option pair, the value of which gives the number of times the % animation is to be looped. Default: 65535. % -delay - option pair, the value of which gives the time, in seconds, % between frames. Default: 1/15. % Copyright (C) Oliver Woodford 2011 function im2gif(A, varargin) % Parse the input arguments [A, options] = parse_args(A, varargin{:}); if options.crop ~= 0 % Crop A = crop_borders(A, A(ceil(end/2),1,:,1)); end % Convert to indexed image [h, w, c, n] = size(A); A = reshape(permute(A, [1 2 4 3]), h, w*n, c); map = unique(reshape(A, h*w*n, c), 'rows'); if size(map, 1) > 256 dither_str = {'dither', 'nodither'}; dither_str = dither_str{1+(options.dither==0)}; if options.ncolors <= 1 [B, map] = rgb2ind(A, options.ncolors, dither_str); if size(map, 1) > 256 [B, map] = rgb2ind(A, 256, dither_str); end else [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str); end else if max(map(:)) > 1 map = double(map) / 255; A = double(A) / 255; end B = rgb2ind(im2double(A), map); end B = reshape(B, h, w, 1, n); % Bug fix to rgb2ind map(B(1)+1,:) = im2double(A(1,1,:)); % Save as a gif imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay); end %% Parse the input arguments function [A, options] = parse_args(A, varargin) % Set the defaults options = struct('outfile', '', ... 'dither', true, ... 'crop', true, ... 'ncolors', 256, ... 'loops', 65535, ... 'delay', 1/15); % Go through the arguments a = 0; n = numel(varargin); while a < n a = a + 1; if ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' opt = lower(varargin{a}(2:end)); switch opt case 'nocrop' options.crop = false; case 'nodither' options.dither = false; otherwise if ~isfield(options, opt) error('Option %s not recognized', varargin{a}); end a = a + 1; if ischar(varargin{a}) && ~ischar(options.(opt)) options.(opt) = str2double(varargin{a}); else options.(opt) = varargin{a}; end end else options.outfile = varargin{a}; end end end if isempty(options.outfile) if ~ischar(A) error('No output filename given.'); end % Generate the output filename from the input filename [path, outfile] = fileparts(A); options.outfile = fullfile(path, [outfile '.gif']); end if ischar(A) % Read in the image A = imread_rgb(A); end end %% Read image to uint8 rgb array function [A, alpha] = imread_rgb(name) % Get file info info = imfinfo(name); % Special case formats switch lower(info(1).Format) case 'gif' [A, map] = imread(name, 'frames', 'all'); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 A = permute(A, [1 2 5 4 3]); end case {'tif', 'tiff'} A = cell(numel(info), 1); for a = 1:numel(A) [A{a}, map] = imread(name, 'Index', a, 'Info', info); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 end if size(A{a}, 3) == 4 % TIFF in CMYK colourspace - convert to RGB if isfloat(A{a}) A{a} = A{a} * 255; else A{a} = single(A{a}); end A{a} = 255 - A{a}; A{a}(:,:,4) = A{a}(:,:,4) / 255; A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4])); end end A = cat(4, A{:}); otherwise [A, map, alpha] = imread(name); A = A(:,:,:,1); % Keep only first frame of multi-frame files if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 elseif size(A, 3) == 4 % Assume 4th channel is an alpha matte alpha = A(:,:,4); A = A(:,:,1:3); end end end
github
vitoruapt/lartkv5-master
read_write_entire_textfile.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/read_write_entire_textfile.m
924
utf_8
779e56972f5d9778c40dee98ddbd677e
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory % % Read or write an entire text file to/from memory, without leaving the % file open if an error occurs. % % Reading: % fstrm = read_write_entire_textfile(fname) % Writing: % read_write_entire_textfile(fname, fstrm) % %IN: % fname - Pathname of text file to be read in. % fstrm - String to be written to the file, including carriage returns. % %OUT: % fstrm - String read from the file. If an fstrm input is given the % output is the same as that input. function fstrm = read_write_entire_textfile(fname, fstrm) modes = {'rt', 'wt'}; writing = nargin > 1; fh = fopen(fname, modes{1+writing}); if fh == -1 error('Unable to open file %s.', fname); end try if writing fwrite(fh, fstrm, 'char*1'); else fstrm = fread(fh, '*char')'; end catch ex fclose(fh); rethrow(ex); end fclose(fh); end
github
vitoruapt/lartkv5-master
pdf2eps.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/pdf2eps.m
1,471
utf_8
a1f41f0c7713c73886a2323e53ed982b
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status, message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); end
github
vitoruapt/lartkv5-master
print2array.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/print2array.m
6,273
utf_8
c2feb752d8836426a74edd9357f1ff17
%PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2012 % 05/09/11: Set EraseModes to normal when using opengl or zbuffer % renderers. Thanks to Pawel Kocieniewski for reporting the % issue. % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting % the issue. % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure % size and erasemode settings. Makes it a bit slower, but more % reliable. Thanks to Phil Trinh and Meelis Lootus for reporting % the issues. % 09/12/11: Pass font path to ghostscript. % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting % it. % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for % reporting the issue. function [A, bcol] = print2array(fig, res, renderer) % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; if nargin > 2 && strcmp(renderer, '-painters') % Print to eps file tmp_eps = [tempname '.eps']; print2eps(tmp_eps, fig, 0, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"']; % Execute the ghostscript command ghostscript(cmd_str); catch me % Delete the intermediate file delete(tmp_eps); rethrow(me); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end err = false; % Set paper size old_pos_mode = get(fig, 'PaperPositionMode'); old_orientation = get(fig, 'PaperOrientation'); set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); try % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end % Reset paper size set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); % Throw any error that occurred if err rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = [px([4 3])*res 3]; if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
vitoruapt/lartkv5-master
append_pdfs.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/append_pdfs.m
2,010
utf_8
1034abde9642693c404671ff1c693a22
%APPEND_PDFS Appends/concatenates multiple PDF files % % Example: % append_pdfs(output, input1, input2, ...) % append_pdfs(output, input_list{:}) % append_pdfs test.pdf temp1.pdf temp2.pdf % % This function appends multiple PDF files to an existing PDF file, or % concatenates them into a PDF file if the output file doesn't yet exist. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % IN: % output - string of output file name (including the extension, .pdf). % If it exists it is appended to; if not, it is created. % input1 - string of an input file name (including the extension, .pdf). % All input files are appended in order. % input_list - cell array list of input file name strings. All input % files are appended in order. % Copyright: Oliver Woodford, 2011 % Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in % one go is much faster than appending them one at a time. % Thanks to Michael Teo for reporting the issue of a too long command line. % Issue resolved on 5/5/2011, by passing gs a command file. % Thanks to Martin Wittmann for pointing out the quality issue when % appending multiple bitmaps. % Issue resolved (to best of my ability) 1/6/2011, using the prepress % setting function append_pdfs(varargin) % Are we appending or creating a new file append = exist(varargin{1}, 'file') == 2; if append output = [tempname '.pdf']; else output = varargin{1}; varargin = varargin(2:end); end % Create the command file cmdfile = [tempname '.txt']; fh = fopen(cmdfile, 'w'); fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output); fprintf(fh, ' "%s"', varargin{:}); fclose(fh); % Call ghostscript ghostscript(['@"' cmdfile '"']); % Delete the command file delete(cmdfile); % Rename the file if needed if append movefile(output, varargin{1}); end end
github
vitoruapt/lartkv5-master
using_hg2.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/using_hg2.m
365
utf_8
6a7f56042fda1873d8225eb3ec1cc197
%USING_HG2 Determine if the HG2 graphics pipeline is used % % tf = using_hg2(fig) % %IN: % fig - handle to the figure in question. % %OUT: % tf - boolean indicating whether the HG2 graphics pipeline is being used % (true) or not (false). function tf = using_hg2(fig) try tf = ~graphicsversion(fig, 'handlegraphics'); catch tf = false; end end
github
vitoruapt/lartkv5-master
eps2pdf.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/eps2pdf.m
5,009
utf_8
5658b3d96232e138be7fd49693d88453
%EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % %IN: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed to % already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale or % not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % Copyright (C) Oliver Woodford 2009-2011 % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. function eps2pdf(source, dest, crop, append, gray, quality) % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status, message] = ghostscript(options); catch me % Delete the intermediate file delete(tmp_nam); rethrow(me); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status, message] = ghostscript(options); end % Check for error if status % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); else error(message); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
vitoruapt/lartkv5-master
copyfig.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/copyfig.m
812
utf_8
b6b1fa9a9351df33ae0d42056c3df40a
%COPYFIG Create a copy of a figure, without changing the figure % % Examples: % fh_new = copyfig(fh_old) % % This function will create a copy of a figure, but not change the figure, % as copyobj sometimes does, e.g. by changing legends. % % IN: % fh_old - The handle of the figure to be copied. Default: gcf. % % OUT: % fh_new - The handle of the created figure. % Copyright (C) Oliver Woodford 2012 function fh = copyfig(fh) % Set the default if nargin == 0 fh = gcf; end % Is there a legend? if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend')) % Safe to copy using copyobj fh = copyobj(fh, 0); else % copyobj will change the figure, so save and then load it instead tmp_nam = [tempname '.fig']; hgsave(fh, tmp_nam); fh = hgload(tmp_nam); delete(tmp_nam); end end
github
vitoruapt/lartkv5-master
user_string.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/user_string.m
2,460
utf_8
e8aa836a5140410546fceccb4cca47aa
%USER_STRING Get/set a user specific string % % Examples: % string = user_string(string_name) % saved = user_string(string_name, new_string) % % Function to get and set a string in a system or user specific file. This % enables, for example, system specific paths to binaries to be saved. % % IN: % string_name - String containing the name of the string required. The % string is extracted from a file called (string_name).txt, % stored in the same directory as user_string.m. % new_string - The new string to be saved under the name given by % string_name. % % OUT: % string - The currently saved string. Default: ''. % saved - Boolean indicating whether the save was succesful % Copyright (C) Oliver Woodford 2011-2013 % This method of saving paths avoids changing .m files which might be in a % version control system. Instead it saves the user dependent paths in % separate files with a .txt extension, which need not be checked in to % the version control system. Thank you to Jonas Dorn for suggesting this % approach. % 10/01/2013 - Access files in text, not binary mode, as latter can cause % errors. Thanks to Christian for pointing this out. function string = user_string(string_name, string) if ~ischar(string_name) error('string_name must be a string.'); end % Create the full filename string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']); if nargin > 1 % Set string if ~ischar(string) error('new_string must be a string.'); end % Make sure the save directory exists dname = fileparts(string_name); if ~exist(dname, 'dir') % Create the directory try if ~mkdir(dname) string = false; return end catch string = false; return end % Make it hidden try fileattrib(dname, '+h'); catch end end % Write the file fid = fopen(string_name, 'wt'); if fid == -1 string = false; return end try fprintf(fid, '%s', string); catch fclose(fid); string = false; return end fclose(fid); string = true; else % Get string fid = fopen(string_name, 'rt'); if fid == -1 string = ''; return end string = fgetl(fid); fclose(fid); end end
github
vitoruapt/lartkv5-master
export_fig.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/export_fig.m
29,720
utf_8
923dcc1ad89f1381ee70abbf422b20a5
%EXPORT_FIG Exports figures suitable for publication % % Examples: % im = export_fig % [im alpha] = export_fig % export_fig filename % export_fig filename -format1 -format2 % export_fig ... -nocrop % export_fig ... -transparent % export_fig ... -native % export_fig ... -m<val> % export_fig ... -r<val> % export_fig ... -a<val> % export_fig ... -q<val> % export_fig ... -p<val> % export_fig ... -<renderer> % export_fig ... -<colorspace> % export_fig ... -append % export_fig ... -bookmark % export_fig(..., handle) % % This function saves a figure or single axes to one or more vector and/or % bitmap file formats, and/or outputs a rasterized version to the % workspace, with the following properties: % - Figure/axes reproduced as it appears on screen % - Cropped borders (optional) % - Embedded fonts (vector formats) % - Improved line and grid line styles % - Anti-aliased graphics (bitmap formats) % - Render images at native resolution (optional for bitmap formats) % - Transparent background supported (pdf, eps, png) % - Semi-transparent patch objects supported (png only) % - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff) % - Variable image compression, including lossless (pdf, eps, jpg) % - Optionally append to file (pdf, tiff) % - Vector formats: pdf, eps % - Bitmap formats: png, tiff, jpg, bmp, export to workspace % % This function is especially suited to exporting figures for use in % publications and presentations, because of the high quality and % portability of media produced. % % Note that the background color and figure dimensions are reproduced % (the latter approximately, and ignoring cropping & magnification) in the % output file. For transparent background (and semi-transparent patch % objects), use the -transparent option or set the figure 'Color' property % to 'none'. To make axes transparent set the axes 'Color' property to % 'none'. Pdf, eps and png are the only file formats to support a % transparent background, whilst the png format alone supports transparency % of patch objects. % % The choice of renderer (opengl, zbuffer or painters) has a large impact % on the quality of output. Whilst the default value (opengl for bitmaps, % painters for vector formats) generally gives good results, if you aren't % satisfied then try another renderer. Notes: 1) For vector formats (eps, % pdf), only painters generates vector graphics. 2) For bitmaps, only % opengl can render transparent patch objects correctly. 3) For bitmaps, % only painters will correctly scale line dash and dot lengths when % magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when % using painters. % % When exporting to vector format (pdf & eps) and bitmap format using the % painters renderer, this function requires that ghostscript is installed % on your system. You can download this from: % http://www.ghostscript.com % When exporting to eps it additionally requires pdftops, from the Xpdf % suite of functions. You can download this from: % http://www.foolabs.com/xpdf % %IN: % filename - string containing the name (optionally including full or % relative path) of the file the figure is to be saved as. If % a path is not specified, the figure is saved in the current % directory. If no name and no output arguments are specified, % the default name, 'export_fig_out', is used. If neither a % file extension nor a format are specified, a ".png" is added % and the figure saved in that format. % -format1, -format2, etc. - strings containing the extensions of the % file formats the figure is to be saved as. % Valid options are: '-pdf', '-eps', '-png', % '-tif', '-jpg' and '-bmp'. All combinations % of formats are valid. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -transparent - option indicating that the figure background is to be % made transparent (png, pdf and eps output only). % -m<val> - option where val indicates the factor to magnify the % on-screen figure pixel dimensions by when generating bitmap % outputs. Default: '-m1'. % -r<val> - option val indicates the resolution (in pixels per inch) to % export bitmap and vector outputs at, keeping the dimensions % of the on-screen figure. Default: '-r864' (for vector output % only). Note that the -m option overides the -r option for % bitmap outputs only. % -native - option indicating that the output resolution (when outputting % a bitmap format) should be such that the vertical resolution % of the first suitable image found in the figure is at the % native resolution of that image. To specify a particular % image to use, give it the tag 'export_fig_native'. Notes: % This overrides any value set with the -m and -r options. It % also assumes that the image is displayed front-to-parallel % with the screen. The output resolution is approximate and % should not be relied upon. Anti-aliasing can have adverse % effects on image quality (disable with the -a1 option). % -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to % use for bitmap outputs. '-a1' means no anti- % aliasing; '-a4' is the maximum amount (default). % -<renderer> - option to force a particular renderer (painters, opengl % or zbuffer) to be used over the default: opengl for % bitmaps; painters for vector formats. % -<colorspace> - option indicating which colorspace color figures should % be saved in: RGB (default), CMYK or gray. CMYK is only % supported in pdf, eps and tiff output. % -q<val> - option to vary bitmap image quality (in pdf, eps and jpg % files only). Larger val, in the range 0-100, gives higher % quality/lower compression. val > 100 gives lossless % compression. Default: '-q95' for jpg, ghostscript prepress % default for pdf & eps. Note: lossless compression can % sometimes give a smaller file size than the default lossy % compression, depending on the type of images. % -p<val> - option to add a border of width val to eps and pdf files, % where val is in units of the intermediate eps file. Default: % 0 (i.e. no padding). % -append - option indicating that if the file (pdfs only) already % exists, the figure is to be appended as a new page, instead % of being overwritten (default). % -bookmark - option to indicate that a bookmark with the name of the % figure is to be created in the output file (pdf only). % handle - The handle of the figure, axes or uipanels (can be an array of % handles, but the objects must be in the same figure) to be % saved. Default: gcf. % %OUT: % im - MxNxC uint8 image array of the figure. % alpha - MxN single array of alphamatte values in range [0,1], for the % case when the background is transparent. % % Some helpful examples and tips can be found at: % https://github.com/ojwoodford/export_fig % % See also PRINT, SAVEAS. % Copyright (C) Oliver Woodford 2008-2014 % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG % (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782). % The idea for using pdftops came from the MATLAB newsgroup (id: 168171). % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928). % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id: % 20979). % The idea of appending figures in pdfs came from Matt C in comments on the % FEX (id: 23629) % Thanks to Roland Martin for pointing out the colour MATLAB % bug/feature with colorbar axes and transparent backgrounds. % Thanks also to Andrew Matthews for describing a bug to do with the figure % size changing in -nodisplay mode. I couldn't reproduce it, but included a % fix anyway. % Thanks to Tammy Threadgill for reporting a bug where an axes is not % isolated from gui objects. % 23/02/12: Ensure that axes limits don't change during printing % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for % reporting it). % 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling % bookmarking of figures in pdf files. % 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep % tick marks fixed. % 12/12/12: Add support for isolating uipanels. Thanks to michael for % suggesting it. % 25/09/13: Add support for changing resolution in vector formats. Thanks % to Jan Jaap Meijer for suggesting it. % 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner % for suggesting it. function [im, alpha] = export_fig(varargin) % Make sure the figure is rendered correctly _now_ so that properties like % axes limits are up-to-date. drawnow; % Parse the input arguments [fig, options] = parse_args(nargout, varargin{:}); % Isolate the subplot, if it is one cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'})); if cls % Given handles of one or more axes, so isolate them from the rest fig = isolate_axes(fig); else % Check we have a figure if ~isequal(get(fig, 'Type'), 'figure'); error('Handle must be that of a figure, axes or uipanel'); end % Get the old InvertHardcopy mode old_mode = get(fig, 'InvertHardcopy'); end % Hack the font units where necessary (due to a font rendering bug in % print?). This may not work perfectly in all cases. Also it can change the % figure layout if reverted, so use a copy. magnify = options.magnify * options.aa_factor; if isbitmap(options) && magnify ~= 1 fontu = findobj(fig, 'FontUnits', 'normalized'); if ~isempty(fontu) % Some normalized font units found if ~cls fig = copyfig(fig); set(fig, 'Visible', 'off'); fontu = findobj(fig, 'FontUnits', 'normalized'); cls = true; end set(fontu, 'FontUnits', 'points'); end end % MATLAB "feature": axes limits and tick marks can change when printing Hlims = findall(fig, 'Type', 'axes'); if ~cls % Record the old axes limit and tick modes Xlims = make_cell(get(Hlims, 'XLimMode')); Ylims = make_cell(get(Hlims, 'YLimMode')); Zlims = make_cell(get(Hlims, 'ZLimMode')); Xtick = make_cell(get(Hlims, 'XTickMode')); Ytick = make_cell(get(Hlims, 'YTickMode')); Ztick = make_cell(get(Hlims, 'ZTickMode')); end % Set all axes limit and tick modes to manual, so the limits and ticks can't change set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual'); set_tick_mode(Hlims, 'X'); set_tick_mode(Hlims, 'Y'); set_tick_mode(Hlims, 'Z'); % Set to print exactly what is there set(fig, 'InvertHardcopy', 'off'); % Set the renderer switch options.renderer case 1 renderer = '-opengl'; case 2 renderer = '-zbuffer'; case 3 renderer = '-painters'; otherwise renderer = '-opengl'; % Default for bitmaps end % Do the bitmap formats first if isbitmap(options) % Get the background colour if options.transparent && (options.png || options.alpha) % Get out an alpha channel % MATLAB "feature": black colorbar axes can change to white and vice versa! hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar'); if isempty(hCB) yCol = []; xCol = []; else yCol = get(hCB, 'YColor'); xCol = get(hCB, 'XColor'); if iscell(yCol) yCol = cell2mat(yCol); xCol = cell2mat(xCol); end yCol = sum(yCol, 2); xCol = sum(xCol, 2); end % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); % Set the background colour to black, and set size in case it was % changed internally tcol = get(fig, 'Color'); set(fig, 'Color', 'k', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==0), 'YColor', [0 0 0]); set(hCB(xCol==0), 'XColor', [0 0 0]); % Print large version to array B = print2array(fig, magnify, renderer); % Downscale the image B = downsize(single(B), options.aa_factor); % Set background to white (and set size) set(fig, 'Color', 'w', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==3), 'YColor', [1 1 1]); set(hCB(xCol==3), 'XColor', [1 1 1]); % Print large version to array A = print2array(fig, magnify, renderer); % Downscale the image A = downsize(single(A), options.aa_factor); % Set the background colour (and size) back to normal set(fig, 'Color', tcol, 'Position', pos); % Compute the alpha map alpha = round(sum(B - A, 3)) / (255 * 3) + 1; A = alpha; A(A==0) = 1; A = B ./ A(:,:,[1 1 1]); clear B % Convert to greyscale if options.colourspace == 2 A = rgb2grey(A); end A = uint8(A); % Crop the background if options.crop [alpha, v] = crop_borders(alpha, 0, 1); A = A(v(1):v(2),v(3):v(4),:); end if options.png % Compute the resolution res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; % Save the png imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); % Clear the png bit options.png = false; end % Return only one channel for greyscale if isbitmap(options) A = check_greyscale(A); end if options.alpha % Store the image im = A; % Clear the alpha bit options.alpha = false; end % Get the non-alpha image if isbitmap(options) alph = alpha(:,:,ones(1, size(A, 3))); A = uint8(single(A) .* alph + 255 * (1 - alph)); clear alph end if options.im % Store the new image im = A; end else % Print large version to array if options.transparent % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); tcol = get(fig, 'Color'); set(fig, 'Color', 'w', 'Position', pos); A = print2array(fig, magnify, renderer); set(fig, 'Color', tcol, 'Position', pos); tcol = 255; else [A, tcol] = print2array(fig, magnify, renderer); end % Crop the background if options.crop A = crop_borders(A, tcol, 1); end % Downscale the image A = downsize(A, options.aa_factor); if options.colourspace == 2 % Convert to greyscale A = rgb2grey(A); else % Return only one channel for greyscale A = check_greyscale(A); end % Outputs if options.im im = A; end if options.alpha im = A; alpha = zeros(size(A, 1), size(A, 2), 'single'); end end % Save the images if options.png res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); end if options.bmp imwrite(A, [options.name '.bmp']); end % Save jpeg with given quality if options.jpg quality = options.quality; if isempty(quality) quality = 95; end if quality > 100 imwrite(A, [options.name '.jpg'], 'Mode', 'lossless'); else imwrite(A, [options.name '.jpg'], 'Quality', quality); end end % Save tif images in cmyk if wanted (and possible) if options.tif if options.colourspace == 1 && size(A, 3) == 3 A = double(255 - A); K = min(A, [], 3); K_ = 255 ./ max(255 - K, 1); C = (A(:,:,1) - K) .* K_; M = (A(:,:,2) - K) .* K_; Y = (A(:,:,3) - K) .* K_; A = uint8(cat(3, C, M, Y, K)); clear C M Y K K_ end append_mode = {'overwrite', 'append'}; imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1}); end end % Now do the vector formats if isvector(options) % Set the default renderer to painters if ~options.renderer renderer = '-painters'; end % Generate some filenames tmp_nam = [tempname '.eps']; if options.pdf pdf_nam = [options.name '.pdf']; else pdf_nam = [tempname '.pdf']; end % Generate the options for print p2eArgs = {renderer, sprintf('-r%d', options.resolution)}; if options.colourspace == 1 p2eArgs = [p2eArgs {'-cmyk'}]; end if ~options.crop p2eArgs = [p2eArgs {'-loose'}]; end try % Generate an eps print2eps(tmp_nam, fig, options.bb_padding, p2eArgs{:}); % Remove the background, if desired if options.transparent && ~isequal(get(fig, 'Color'), 'none') eps_remove_background(tmp_nam, 1 + using_hg2(fig)); end % Add a bookmark to the PDF if desired if options.bookmark fig_nam = get(fig, 'Name'); if isempty(fig_nam) warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.'); end add_bookmark(tmp_nam, fig_nam); end % Generate a pdf eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality); catch ex % Delete the eps delete(tmp_nam); rethrow(ex); end % Delete the eps delete(tmp_nam); if options.eps try % Generate an eps from the pdf pdf2eps(pdf_nam, [options.name '.eps']); catch ex if ~options.pdf % Delete the pdf delete(pdf_nam); end rethrow(ex); end if ~options.pdf % Delete the pdf delete(pdf_nam); end end end if cls % Close the created figure close(fig); else % Reset the hardcopy mode set(fig, 'InvertHardcopy', old_mode); % Reset the axes limit and tick modes for a = 1:numel(Hlims) set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a}); end end end function [fig, options] = parse_args(nout, varargin) % Parse the input arguments % Set the defaults fig = get(0, 'CurrentFigure'); options = struct('name', 'export_fig_out', ... 'crop', true, ... 'transparent', false, ... 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters 'pdf', false, ... 'eps', false, ... 'png', false, ... 'tif', false, ... 'jpg', false, ... 'bmp', false, ... 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray 'append', false, ... 'im', nout == 1, ... 'alpha', nout == 2, ... 'aa_factor', 0, ... 'bb_padding', 0, ... 'magnify', [], ... 'resolution', [], ... 'bookmark', false, ... 'quality', []); native = false; % Set resolution to native of an image % Go through the other arguments for a = 1:nargin-1 if all(ishandle(varargin{a})) fig = varargin{a}; elseif ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' switch lower(varargin{a}(2:end)) case 'nocrop' options.crop = false; case {'trans', 'transparent'} options.transparent = true; case 'opengl' options.renderer = 1; case 'zbuffer' options.renderer = 2; case 'painters' options.renderer = 3; case 'pdf' options.pdf = true; case 'eps' options.eps = true; case 'png' options.png = true; case {'tif', 'tiff'} options.tif = true; case {'jpg', 'jpeg'} options.jpg = true; case 'bmp' options.bmp = true; case 'rgb' options.colourspace = 0; case 'cmyk' options.colourspace = 1; case {'gray', 'grey'} options.colourspace = 2; case {'a1', 'a2', 'a3', 'a4'} options.aa_factor = str2double(varargin{a}(3)); case 'append' options.append = true; case 'bookmark' options.bookmark = true; case 'native' native = true; otherwise val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match')); if ~isscalar(val) error('option %s not recognised', varargin{a}); end switch lower(varargin{a}(2)) case 'm' options.magnify = val; case 'r' options.resolution = val; case 'q' options.quality = max(val, 0); case 'p' options.bb_padding = val; end end else [p, options.name, ext] = fileparts(varargin{a}); if ~isempty(p) options.name = [p filesep options.name]; end switch lower(ext) case {'.tif', '.tiff'} options.tif = true; case {'.jpg', '.jpeg'} options.jpg = true; case '.png' options.png = true; case '.bmp' options.bmp = true; case '.eps' options.eps = true; case '.pdf' options.pdf = true; otherwise options.name = varargin{a}; end end end end % Set default anti-aliasing now we know the renderer if options.aa_factor == 0 options.aa_factor = 1 + 2 * (~(using_hg2(fig) && strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on')) | (options.renderer == 3)); end % Convert user dir '~' to full path if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\') options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end)); end % Compute the magnification and resolution if isempty(options.magnify) if isempty(options.resolution) options.magnify = 1; options.resolution = 864; else options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch'); end elseif isempty(options.resolution) options.resolution = 864; end % Check we have a figure handle if isempty(fig) error('No figure found'); end % Set the default format if ~isvector(options) && ~isbitmap(options) options.png = true; end % Check whether transparent background is wanted (old way) if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none') options.transparent = true; end % If requested, set the resolution to the native vertical resolution of the % first suitable image found if native && isbitmap(options) % Find a suitable image list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native'); if isempty(list) list = findobj(fig, 'Type', 'image', 'Visible', 'on'); end for hIm = list(:)' % Check height is >= 2 height = size(get(hIm, 'CData'), 1); if height < 2 continue end % Account for the image filling only part of the axes, or vice % versa yl = get(hIm, 'YData'); if isscalar(yl) yl = [yl(1)-0.5 yl(1)+height+0.5]; else if ~diff(yl) continue end yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1)); end hAx = get(hIm, 'Parent'); yl2 = get(hAx, 'YLim'); % Find the pixel height of the axes oldUnits = get(hAx, 'Units'); set(hAx, 'Units', 'pixels'); pos = get(hAx, 'Position'); set(hAx, 'Units', oldUnits); if ~pos(4) continue end % Found a suitable image % Account for stretch-to-fill being disabled pbar = get(hAx, 'PlotBoxAspectRatio'); pos = min(pos(4), pbar(2)*pos(3)/pbar(1)); % Set the magnification to give native resolution options.magnify = (height * diff(yl2)) / (pos * diff(yl)); break end end end function A = downsize(A, factor) % Downsample an image if factor == 1 % Nothing to do return end try % Faster, but requires image processing toolbox A = imresize(A, 1/factor, 'bilinear'); catch % No image processing toolbox - resize manually % Lowpass filter - use Gaussian as is separable, so faster % Compute the 1d Gaussian filter filt = (-factor-1:factor+1) / (factor * 0.6); filt = exp(-filt .* filt); % Normalize the filter filt = single(filt / sum(filt)); % Filter the image padding = floor(numel(filt) / 2); for a = 1:size(A, 3) A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid'); end % Subsample A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:); end end function A = rgb2grey(A) A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); end function A = check_greyscale(A) % Check if the image is greyscale if size(A, 3) == 3 && ... all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ... all(reshape(A(:,:,2) == A(:,:,3), [], 1)) A = A(:,:,1); % Save only one channel for 8-bit output end end function eps_remove_background(fname, count) % Remove the background of an eps file % Open the file fh = fopen(fname, 'r+'); if fh == -1 error('Not able to open file %s.', fname); end % Read the file line by line while count % Get the next line l = fgets(fh); if isequal(l, -1) break; % Quit, no rectangle found end % Check if the line contains the background rectangle if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1) % Set the line to whitespace and quit l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' '; fseek(fh, -numel(l), 0); fprintf(fh, l); % Reduce the count count = count - 1; end end % Close the file fclose(fh); end function b = isvector(options) b = options.pdf || options.eps; end function b = isbitmap(options) b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha; end % Helper function function A = make_cell(A) if ~iscell(A) A = {A}; end end function add_bookmark(fname, bookmark_text) % Adds a bookmark to the temporary EPS file after %%EndPageSetup % Read in the file fh = fopen(fname, 'r'); if fh == -1 error('File %s not found.', fname); end try fstrm = fread(fh, '*char')'; catch ex fclose(fh); rethrow(ex); end fclose(fh); % Include standard pdfmark prolog to maximize compatibility fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse')); % Add page bookmark fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text)); % Write out the updated file fh = fopen(fname, 'w'); if fh == -1 error('Unable to open %s for writing.', fname); end try fwrite(fh, fstrm, 'char*1'); catch ex fclose(fh); rethrow(ex); end fclose(fh); end function set_tick_mode(Hlims, ax) % Set the tick mode of linear axes to manual % Leave log axes alone as these are tricky M = get(Hlims, [ax 'Scale']); if ~iscell(M) M = {M}; end M = cellfun(@(c) strcmp(c, 'linear'), M); set(Hlims(M), [ax 'TickMode'], 'manual'); end
github
vitoruapt/lartkv5-master
ghostscript.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/ghostscript.m
5,009
utf_8
e93de4034ac6e4ac154729dc2c12f725
%GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2013 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Nathan Childress for the fix to the default location on 64-bit % Windows systems. % 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 4/5/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish % Punnoose for highlighting the issue. % 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick % Steinbring for proposing the fix. % 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes % for the fix. % 23/01/2014 - Add full path to ghostscript.txt in warning. Thanks to Koen % Vermeer for raising the issue. function varargout = ghostscript(cmd) % Initialize any required system calls before calling ghostscript shell_cmd = ''; if isunix shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07 end if ismac shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07 end % Call ghostscript [varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd)); end function path_ = gs_path % Return a valid path % Start with the currently set path path_ = user_string('ghostscript'); % Check the path works if check_gs_path(path_) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; else bin = {'gs'}; end for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path_ = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path_) return end else executable = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(executable) path_ = executable{a}; if check_store_gs_path(path_) return end end end % Ask the user to enter the path while 1 if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path_ = [base bin_dir{a} bin{b}]; if exist(path_, 'file') == 2 if check_store_gs_path(path_) return end end end end end error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); end function good = check_store_gs_path(path_) % Check the path is valid good = check_gs_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path_) warning('Path to ghostscript installation could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt')); return end end function good = check_gs_path(path_) % Check the path is valid shell_cmd = ''; if ismac shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07 end [good, message] = system(sprintf('%s"%s" -h', shell_cmd, path_)); good = good == 0; end
github
vitoruapt/lartkv5-master
fix_lines.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/export_fig/fix_lines.m
5,759
utf_8
3338572f35c4669b79cc3265892d35de
%FIX_LINES Improves the line style of eps files generated by print % % Examples: % fix_lines fname % fix_lines fname fname2 % fstrm_out = fixlines(fstrm_in) % % This function improves the style of lines in eps files generated by % MATLAB's print function, making them more similar to those seen on % screen. Grid lines are also changed from a dashed style to a dotted % style, for greater differentiation from dashed lines. % % The function also places embedded fonts after the postscript header, in % versions of MATLAB which place the fonts first (R2006b and earlier), in % order to allow programs such as Ghostscript to find the bounding box % information. % %IN: % fname - Name or path of source eps file. % fname2 - Name or path of destination eps file. Default: same as fname. % fstrm_in - File contents of a MATLAB-generated eps file. % %OUT: % fstrm_out - Contents of the eps file with line styles fixed. % Copyright: (C) Oliver Woodford, 2008-2014 % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928) % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % Thank you to Sylvain Favrot for bringing the embedded font/bounding box % interaction in older versions of MATLAB to my attention. % Thank you to D Ko for bringing an error with eps files with tiff previews % to my attention. % Thank you to Laurence K for suggesting the check to see if the file was % opened. function fstrm = fix_lines(fstrm, fname2) if nargout == 0 || nargin > 1 if nargin < 2 % Overwrite the input file fname2 = fstrm; end % Read in the file fstrm = read_write_entire_textfile(fstrm); end % Move any embedded fonts after the postscript header if strcmp(fstrm(1:15), '%!PS-AdobeFont-') % Find the start and end of the header ind = regexp(fstrm, '[\n\r]%!PS-Adobe-'); [ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+'); % Put the header first if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1) fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]); end end % Make sure all line width commands come before the line style definitions, % so that dash lengths can be based on the correct widths % Find all line style sections ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes! regexp(fstrm, '[\n\r]DO[\n\r]'),... regexp(fstrm, '[\n\r]DA[\n\r]'),... regexp(fstrm, '[\n\r]DD[\n\r]')]; ind = sort(ind); % Find line width commands [ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]'); % Go through each line style section and swap with any line width commands % near by b = 1; m = numel(ind); n = numel(ind2); for a = 1:m % Go forwards width commands until we pass the current line style while b <= n && ind2(b) < ind(a) b = b + 1; end if b > n % No more width commands break; end % Check we haven't gone past another line style (including SO!) if a < m && ind2(b) > ind(a+1) continue; end % Are the commands close enough to be confident we can swap them? if (ind2(b) - ind(a)) > 8 continue; end % Move the line style command below the line width command fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)]; b = b + 1; end % Find any grid line definitions and change to GR format % Find the DO sections again as they may have moved ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]')); if ~isempty(ind) % Find all occurrences of what are believed to be axes and grid lines ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]')); if ~isempty(ind2) % Now see which DO sections come just before axes and grid lines ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]); ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right ind = ind(ind2); % Change any regions we believe to be grid lines to GR fstrm(ind+1) = 'G'; fstrm(ind+2) = 'R'; end end % Isolate line style definition section first_sec = strfind(fstrm, '% line types:'); [second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/'); [remaining, remaining] = strtok(remaining, '%'); % Define the new styles, including the new GR format % Dot and dash lengths have two parts: a constant amount plus a line width % variable amount. The constant amount comes after dpi2point, and the % variable amount comes after currentlinewidth. If you want to change % dot/dash lengths for a one particular line style only, edit the numbers % in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and % /GR (grid lines) lines for the style you want to change. new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width '/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width '/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines '/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines '/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines '/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant % Construct the output fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining]; % Write the output file if nargout == 0 || nargin > 1 read_write_entire_textfile(fname2, fstrm); end end
github
vitoruapt/lartkv5-master
unbreakxaxis.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/breakxaxis/unbreakxaxis.m
299
utf_8
27245623b049d3a3f78c2c622c82aeae
function unbreakxaxis(breakInfo) delete(breakInfo.leftAxes); delete(breakInfo.rightAxes); delete(breakInfo.breakAxes); delete(breakInfo.annotationAxes); for i = 1:numel(breakInfo.invisibleObjects) set(breakInfo.invisibleObjects(i),'Visible','on'); end end
github
vitoruapt/lartkv5-master
breakxaxis.m
.m
lartkv5-master/src/perception/pedestrians/multimodal_pedestrian_detection/matlab/breakxaxis/breakxaxis.m
11,663
utf_8
86d70f4a907a88c29fa10ebfec1b904b
% breakxaxes splits data in an axes so that data is in a left and right pane. % % breakXAxes(splitXLim) splitXLim is a 2 element vector containing a range % of x values from splitXLim(1) to splitXLim(2) to remove from the axes. % They must be within the current xLimis of the axes. % % breakXAxes(splitXLim,splitWidth) splitWidth is the distance to % seperate the left and right side. Units are the same as % get(AX,'uints') default is 0.015 % % breakXAxes(splitXLim,splitWidth,yOverhang) yOverhang stretches the % axis split graphic to extend past the top and bottom of the plot by % the distance set by YOverhang. Units are the same as get(AX,'units') % default value is 0.015 % % breakXAxes(AX, ...) performs the operation on the axis specified by AX % function breakInfo = breakxaxis(varargin) %Validate Arguements if nargin < 1 || nargin > 4 error('Wrong number of arguements'); end if isscalar(varargin{1}) && ishandle(varargin{1}) mainAxes = varargin{1}; argOffset = 1; argCnt = nargin - 1; if ~strcmp(get(mainAxes,'Type'),'axes') error('Handle object must be Type Axes'); end else mainAxes = gca; argOffset = 0; argCnt = nargin; end if (strcmp(get(mainAxes,'XScale'),'log')) error('Log X Axes are not supported'); end if (argCnt < 3) yOverhang = 0.015; else yOverhang = varargin{3 + argOffset}; if numel(yOverhang) ~= 1 || ~isreal(yOverhang) || ~isnumeric(yOverhang) error('YOverhang must be a scalar number'); elseif (yOverhang < 0) error('YOverhang must not be negative'); end yOverhang = double(yOverhang); end if (argCnt < 2) splitWidth = 0.015; else splitWidth = varargin{2 + argOffset}; if numel(yOverhang) ~= 1 || ~isreal(yOverhang) || ~isnumeric(yOverhang) error('splitWidth must be a scalar number'); elseif (yOverhang < 0) error('splitWidth must not be negative'); end splitWidth = double(splitWidth); end splitXLim = varargin{1 + argOffset}; if numel(splitXLim) ~= 2 || ~isnumeric(splitXLim) || ~isreal(yOverhang) error(splitXLim,'Must be a vector length 2'); end splitXLim = double(splitXLim); mainXLim = get(mainAxes,'XLim'); if (any(splitXLim >= mainXLim(2)) || any(splitXLim <= mainXLim(1))) error('splitXLim must be in the range given by get(AX,''XLim'')'); end mainPosition = get(mainAxes,'Position'); if (splitWidth > mainPosition(3) ) error('Split width is too large') end %We need to create 4 axes % leftAxes - is used for the left x axis and left pane data % rightAxes - is used to the right x axis and right pane data % annotationAxes - is used to display the y axis and title % breakAxes - this is an axes with the same size and position as main % is it used to draw a seperator between the left and right side %Grab Some Parameters from the main axis (e.g the one we are spliting) mainXLim = get(mainAxes,'XLim'); mainYLim = get(mainAxes,'YLim'); mainPosition = get(mainAxes,'Position'); mainParent = get(mainAxes,'Parent'); mainWidth = mainPosition(3); %Positions have the format [left bottom width height] %mainXRange = mainXLim(2) - mainXLim(1); mainFigure = get(mainAxes,'Parent'); mainYColor = get(mainAxes,'YColor'); mainLineWidth = get(mainAxes,'LineWidth'); figureColor = get(mainFigure,'Color'); mainYTickLabelMode = get(mainAxes,'YTickLabelMode'); mainXLabel = get(mainAxes,'XLabel'); mainXDir = get(mainAxes,'XDir'); mainLayer = get(mainAxes,'Layer'); %Save Main Axis Z Order figureChildren = get(mainFigure,'Children'); zOrder = find(figureChildren == mainAxes); %Calculate where axesLeft and axesRight will be layed on screen %And their respctive XLimits leftXLimTemp = [mainXLim(1) splitXLim(1)]; rightXLimTemp = [splitXLim(2) mainXLim(2)]; leftXRangeTemp = leftXLimTemp(2) - leftXLimTemp(1); rightXRangeTemp = rightXLimTemp(2) - rightXLimTemp(1); leftWidthTemp = leftXRangeTemp / (leftXRangeTemp + rightXRangeTemp) * (mainWidth - splitWidth); rightWidthTemp = rightXRangeTemp / (leftXRangeTemp + rightXRangeTemp) * (mainWidth - splitWidth); leftStretch = (leftWidthTemp + splitWidth/2) / leftWidthTemp; leftXRange = leftXRangeTemp * leftStretch; leftWidth = leftWidthTemp * leftStretch; rightStretch = (rightWidthTemp + splitWidth/2) / rightWidthTemp; rightXRange = rightXRangeTemp * rightStretch; rightWidth = rightWidthTemp * rightStretch; leftXLim = [mainXLim(1) mainXLim(1)+leftXRange]; rightXLim = [mainXLim(2)-rightXRange mainXLim(2)]; if (strcmp(mainXDir, 'normal')) leftPosition = mainPosition; leftPosition(3) = leftWidth; rightPosition = mainPosition; rightPosition(1) = mainPosition(1) + leftWidth; rightPosition(3) = rightWidth; else %Left Axis will actually go on the right side a vise versa rightPosition = mainPosition; rightPosition(3) = rightWidth; leftPosition = mainPosition; leftPosition(1) = mainPosition(1) + rightWidth; leftPosition(3) = leftWidth; end %Create the Annotations layer, if the Layer is top, draw the axes on %top (e.g. after) drawing the left and right pane if strcmp(mainLayer,'bottom') annotationAxes = CreateAnnotaionAxes(mainAxes,mainParent) end %Create and position the leftAxes. Remove all Y Axis Annotations, the %title, and a potentially offensive tick mark leftAxes = copyobj(mainAxes,mainParent); set(leftAxes,'Position', leftPosition, ... 'XLim', leftXLim, ... 'YLim', mainYLim, ... 'YGrid' ,'off', ... 'YMinorGrid', 'off', ... 'YMinorTick','off', ... 'YTick', [], ... 'YTickLabel', [], ... 'box','off'); if strcmp(mainLayer,'bottom') set(leftAxes,'Color','none'); end delete(get(leftAxes,'YLabel')); delete(get(leftAxes,'XLabel')); delete(get(leftAxes,'Title')); if strcmp(mainYTickLabelMode,'auto') xTick = get(leftAxes,'XTick'); set(leftAxes,'XTick',xTick(1:(end-1))); end %Create and position the rightAxes. Remove all Y Axis annotations, the %title, and a potentially offensive tick mark rightAxes = copyobj(mainAxes,mainParent); set(rightAxes,'Position', rightPosition, ... 'XLim', rightXLim, ... 'YLim', mainYLim, ... 'YGrid' ,'off', ... 'YMinorGrid', 'off', ... 'YMinorTick','off', ... 'YTick', [], ... 'YTickLabel', [], ... 'box','off'); if strcmp(mainLayer,'bottom') set(rightAxes,'Color','none'); end delete(get(rightAxes,'YLabel')); delete(get(rightAxes,'XLabel')); delete(get(rightAxes,'Title')); if strcmp(mainYTickLabelMode,'auto') xTick = get(rightAxes,'XTick'); set(rightAxes,'XTick',xTick(2:end)); end %Create the Annotations layer, if the Layer is top, draw the axes on %top (e.g. after) drawing the left and right pane if strcmp(mainLayer,'top') annotationAxes = CreateAnnotaionAxes(mainAxes,mainParent); set(annotationAxes, 'Color','none'); end %Create breakAxes, remove all graphics objects and hide all annotations breakAxes = copyobj(mainAxes,mainParent); children = get(breakAxes,'Children'); for i = 1:numel(children) delete(children(i)); end set(breakAxes,'Color','none'); %Stretch the breakAxes vertically to cover the horzontal axes lines orignalUnits = get(breakAxes,'Units'); set(breakAxes,'Units','Pixel'); breakPosition = get(breakAxes,'Position'); nudgeFactor = get(breakAxes,'LineWidth'); breakPosition(4) = breakPosition(4) + nudgeFactor; set(breakAxes,'Position',breakPosition); set(breakAxes,'Units',orignalUnits); %Stretch the breakAxes vertically to create an overhang for sylistic %effect breakPosition = get(breakAxes,'Position'); breakPosition(2) = breakPosition(2) - yOverhang; breakPosition(4) = breakPosition(4) + 2*yOverhang; set(breakAxes,'Position',breakPosition); %Create a sine shaped patch to seperate the 2 sides breakXLim = [mainPosition(1) mainPosition(1)+mainPosition(3)]; set(breakAxes,'xlim',breakXLim); theta = linspace(0,2*pi,100); yPoints = linspace(mainYLim(1),mainYLim(2),100); amp = splitWidth/2 * 0.9; xPoints1 = amp * sin(theta) + mainPosition(1) + leftWidthTemp; xPoints2 = amp * sin(theta) + mainPosition(1) + mainPosition(3) - rightWidthTemp; patchPointsX = [xPoints1 xPoints2(end:-1:1) xPoints1(1)]; patchPointsY = [yPoints yPoints(end:-1:1) yPoints(1)]; patch(patchPointsX,patchPointsY ,figureColor,'EdgeColor',figureColor,'Parent',breakAxes); %Create A Line To Delineate the left and right edge of the patch line('xData',xPoints1,'ydata',yPoints,'Parent',breakAxes,'Color',mainYColor,'LineWidth',mainLineWidth); line('xData',xPoints2,'ydata',yPoints,'Parent',breakAxes,'Color',mainYColor,'LineWidth',mainLineWidth); set(breakAxes,'Visible','off'); %Make the old main axes invisiable invisibleObjects = RecursiveSetVisibleOff(mainAxes); %Preserve the z-order of the figure uistack([leftAxes rightAxes breakAxes annotationAxes],'down',zOrder-1) %Set the rezise mode to position so that we can dynamically change the %size of the figure without screwing things up set([leftAxes rightAxes breakAxes annotationAxes],'ActivePositionProperty','Position'); %Playing with the titles labels etc can cause matlab to reposition %the axes in some cases. Mannually force the position to be correct. set([breakAxes annotationAxes],'Position',mainPosition); %Save the axes so we can unbreak the axis easily breakInfo = struct(); breakInfo.leftAxes = leftAxes; breakInfo.rightAxes = rightAxes; breakInfo.breakAxes = breakAxes; breakInfo.annotationAxes = annotationAxes; breakInfo.invisibleObjects = invisibleObjects; end function list = RecursiveSetVisibleOff(handle) list = []; list = SetVisibleOff(handle,list); end function list = SetVisibleOff(handle, list) if (strcmp(get(handle,'Visible'),'on')) set(handle,'Visible','off'); list = [list handle]; end children = get(handle,'Children'); for i = 1:numel(children) list = SetVisibleOff(children(i),list); end end function annotationAxes = CreateAnnotaionAxes(mainAxes,mainParent) %Create Annotation Axis, Remove graphics objects, XAxis annotations %(except XLabel) and make background transparent annotationAxes = copyobj(mainAxes,mainParent); set(annotationAxes,'YLimMode','Manual'); children = get(annotationAxes,'Children'); for i = 1:numel(children) delete(children(i)); end %Save the xLabelpostion because it will move when we delete xAxis %ticks xLabel = get(annotationAxes,'XLabel'); xLabelPosition = get(xLabel,'Position'); set(annotationAxes,'XGrid' ,'off', ... 'XMinorGrid', 'off', ... 'XMinorTick','off', ... 'XTick', [], ... 'XTickLabel', []); %Restore the pevious label postition set(xLabel,'Position',xLabelPosition); end
github
vitoruapt/lartkv5-master
ccvGetLaneDetectionStats.m
.m
lartkv5-master/src/perception/road/caltech_lanes/matlab/ccvGetLaneDetectionStats.m
5,767
utf_8
3b1a1bbdb2c02cde9f338e584d4523e4
function ccvGetLaneDetectionStats(detectionFiles, truthFiles) % CCVGETLANEDETECTIONSTATS computes stats for the results compared to the % ground truth % % INPUTS % ------ % detectionFiles - a cell array of the detection files % truthFiles - a cell array of the corresponding ground truth files % % OUTPUTS % ------- % % See also ccvLabel % % Thresholds for merging i.e. matching splines meanDistThreshold = 15; medianDistThreshold = 20; % Initialize allResults = []; allDetectionTotal = 0; allTruthTotal = 0; allNumFrames = 0; allTp = 0; allFp = 0; disp('------------------------------------------------------------------'); for d=1:length(detectionFiles) %get detection and truth file detectionFile = detectionFiles{d}; truthFile = truthFiles{d}; %load the ground truth truths = ccvLabel('read', truthFile); %load the detections file detections = ccvReadLaneDetectionResultsFile(detectionFile); %results for this file results = []; detectionTotal = 0; truthTotal = 0; numFrames = 0; %progress index prog = 0; progress= '-\|/'; fprintf(1, '\n-'); %loop on results and compare splines for i=1:length(detections) %get frame detectionFrame = detections(i); detectionSplines = detectionFrame.splines; %display progress if mod(length(results), 10)==0 fprintf(1, '\b%s', progress(prog+1)); prog = mod(prog+1, length(progress)); end; %get truth splines for that frame truthFrame = ccvLabel('getFrame', truths, i); if isempty(truthFrame), continue; end; numFrames = numFrames + 1; truthSplines = GetTruthSplines(truthFrame.labels); %update totals detectionTotal = detectionTotal + length(detectionSplines); truthTotal = truthTotal + length(truthSplines); %loop on these splines and compare to ground truth to get the closest frameDetections = []; truthDetections = zeros(1, length(truthSplines)); for j=1:length(detectionSplines) %flag detection = 0; %loop on truth and get which one k = 1; while detection==0 && k<=length(truthSplines) if ccvCheckMergeSplines(detectionSplines{j}, ... truthSplines{k}, meanDistThreshold, ... medianDistThreshold); %not false pos detection = 1; truthDetections(k) = 1; end; %inc k = k+1; end; %while %check result result.score = detectionFrame.scores(j); result.detection = detection; results = [results, result]; frameDetections = [frameDetections, detection]; end; %for %get number of missed splines frameNumMissed = length(truthSplines) - length(find(frameDetections==1)); frameNumFalse = length(find(frameDetections==0)); end; % for i %print out some stats tp = length(find([results.detection]==1)); fp = length(find([results.detection]==0)); % numFrames = length(detections); fprintf(1,'\n\n\n'); disp(sprintf('Detection File %d: %s', i, detectionFile)); disp(sprintf('Number of frames = %d', numFrames)); disp(' '); disp(sprintf('Total detections = %d', detectionTotal)); disp(sprintf('Total truth = %d', truthTotal)); disp(' '); disp(sprintf('Number of correct detections = %d', tp)); disp(sprintf('Number of false detections = %d', fp)); disp(' '); disp(sprintf('Percentage of correct detections = %f', tp/truthTotal)); disp(sprintf('Percentage of false detections = %f', fp/truthTotal)); disp(' '); disp(sprintf('False detections/frame= %f', fp/numFrames)); %put in total stats allResults = [allResults, results]; allDetectionTotal = allDetectionTotal + detectionTotal; allTruthTotal = allTruthTotal + truthTotal; allNumFrames = allNumFrames + numFrames; allTp = allTp + tp; allFp = allFp + fp; dResults{d} = results; dDetectionTotal(d) = detectionTotal; dTruthTotal(d) = truthTotal; dNumFrames(d) = numFrames; dTp(d) = tp; dFp(d) = fp; end; %for fprintf(1,'\n\n\n'); disp('Overall results'); disp(sprintf('Number of frames = %d', allNumFrames)); disp(' '); disp(sprintf('Total detections = %d', allDetectionTotal)); disp(sprintf('Total truth = %d', allTruthTotal)); disp(' '); disp(sprintf('Number of correct detections = %d', allTp)); disp(sprintf('Number of false detections = %d', allFp)); disp(' '); disp(sprintf('Percentage of correct detections = %f', allTp/allTruthTotal)); disp(sprintf('Percentage of false detections = %f', allFp/allTruthTotal)); disp(' '); disp(sprintf('False detections/frame= %f', allFp/allNumFrames)); fprintf(1,'\n\n\n-----'); disp('Summary results'); for d=1:length(dDetectionTotal) disp(' '); disp(sprintf('Detection %s', detectionFile)); disp(sprintf('Total = %d', dTruthTotal(d))); disp(sprintf('Total detections = %d', dDetectionTotal(d))); disp(sprintf('correct detections = %.2f', 100*dTp(d)/dTruthTotal(d))); disp(sprintf('false detections = %.2f', 100*dFp(d)/dTruthTotal(d))); disp(sprintf('false detections / frame = %.3f', dFp(d)/dNumFrames(d))); end; % --------------------------------------------------------------------------- function splines = GetTruthSplines(labels) % returns splines in the labels as a cell array of splines splines = {}; for i=1:length(labels) if strcmp(labels(i).type, 'spline') splines{end+1} = labels(i).points; end; end;
github
vitoruapt/lartkv5-master
ccvLabel.m
.m
lartkv5-master/src/perception/road/caltech_lanes/matlab/ccvLabel.m
9,282
utf_8
a4cfee3bd06cea44bcb2ba59e53582b8
function varargout = ccvLabel(f, varargin) % CCVLABEL performs different tasks on the label structure, like creating % new structure, adding frames, labels, ...etc. % % INPUTS % ------ % f - the input function to perform % varargin - the rest of the inputs (potentially zero) % % OUTPUTS % ------- % varargout - the outputs from the selected operation % % See also ccvLabeler % % AUTHOR - Mohamed Aly <[email protected]> % DATE - May 26, 2009 % %check if we have a valid input function if isempty(f) || ~exist(f, 'file'), error('Please enter a valid function'); end; %call the function varargout = cell(1, nargout); [varargout{:}] = feval(f, varargin{:}); end function ld = create() % NEW creates a new empty structure % % INPUTS % ------ % % OUTPUTS % ------- % ld - the output empty label data % ld.version = 0; ld.source = 'image'; ld.frames = struct('frame', {}, ... 'labels', struct('points',{}, 'type',{}, 'subtype',{}, 'obj',{})); ld.objects = struct('id',{}); end function ld = read(fname) % READ loads label data from a file % % INPUTS % ------ % fname - the input file name % % OUTPUTS % ------- % ld - the output empty label data % %load the file ld = []; try load(fname, '-mat'); catch return; end; %check version if ~exist('ld', 'var') || ~ld.version<0 error('invalid input file'); end; %check objects if ~isfield(ld,'objects'), ld.objects = []; end; end function write(fname, ld) %#ok<INUSD> % WRITE saves label data to a file % % INPUTS % ------ % fname - the input file name % ld - the input label data % % OUTPUTS % ------- % %load the file save(fname, 'ld', '-mat'); end function [obj] = createObj(objId) % CREATEOBJ creates a new object and returns it % % INPUTS % ------ % objId - the object id of the new object % % OUTPUTS % ------- % obj - the new obj % obj = struct('id', objId); end function [ld, objId] = addObj(ld) % ADDOBJ adds a new object and returns the object id % % INPUTS % ------ % ld - the input label data % % OUTPUTS % ------- % ld - the output label data % objId - the id of the new object added % %get id of new object objId = max([ld.objects.id]) + 1; if isempty(objId), objId = 1; end; %add it ld.objects = [ld.objects createObj(objId)]; end function ld = removeObj(ld, objId) % REMOVEOBJ deletes an object and clears objects of every label with that % object id % % INPUTS % ------ % ld - the input label data % objId - the id of the object to remove % % OUTPUTS % ------- % ld - the output label data % %get index of object objInd = find([ld.objects.id] == objId); %make sure it's valid if ~isempty(objInd) %clear it ld.objects(objInd) = []; %update all labels with that object id, loop all frames and check for f=1:length(ld.frames) %reset labels with that object label for l=1:length(ld.frames(f).labels) if ld.frames(f).labels(l).obj == objId, ld.frames(f).labels(l).obj = []; end; end; % lbls = find([ld.frames(f).labels.obj] == objId); % for l=lbls, ld.frames(f).labels(l).obj = []; end; end; end; %if end function [objIds] = getObjIds(ld) % GETOBJIDS returns the object ids present % % INPUTS % ------ % ld - the input label data % % OUTPUTS % ------- % objIds - the list of object ids % %get ids of objects objIds = [ld.objects.id]; end function nframes = nFrames(ld) % NFRAMES returns the number of frames % % INPUTS % ------ % ld - the input label data % % OUTPUTS % ------- % nframes - the number of frames % %get the frame nframes = length(ld.frames); end function frame = getFrame(ld, frameIdx) % GETFRAME returns the required frame % % INPUTS % ------ % ld - the input label data % frameIdx - the frame index % % OUTPUTS % ------- % frame - the returned frame, which is a structure with fields % .frame - the index or file name of the frame % .labels - the array of labels in this frame % %get the frame frame = ld.frames(frameIdx); end function frm = createFrame(frame, labels) % CREATEFRAME creates a new frame % % INPUTS % ------ % frame - the frame id or file name % labels - the frame labels % % OUTPUTS % ------- % frm - the output new frame % if nargin<1, frame = []; end; if nargin<2, labels = createLabel(); end; %create the new frame frm = struct('frame',frame, 'labels',labels); end function [ld, frameIdx] = addFrame(ld, frame, labels) % ADDFRAME adds a frame into the data structure % % INPUTS % ------ % ld - the input label data % frame - the frame id or file name % labels - the frame labels % % OUTPUTS % ------- % ld - the update ld structure % frameIdx - the index of the new frame % if nargin<2, frame = []; end; if nargin<3, labels = createLabel(); end; %get the frame index frameIdx = length(ld.frames) + 1; %put the new frame ld.frames(frameIdx) = createFrame(frame, labels); end function ld = removeFrame(ld, frameIdx) % REMOVEFRAME removes the frame % % INPUTS % ------ % ld - the input label data % frameIdx - the frame index % % OUTPUTS % ------- % ld - the update ld structure % %remove the frame ld.frames(frameIdx) = []; end function label = createLabel(points, type, subtype, objId) % CREATELABEL creates a new label % % INPUTS % ------ % points - the points for that label % type - the type of label % subtype - the subtype of the label % objId - the objId of the label % % OUTPUTS % ------- % ld - the output updated label data % if nargin<1, points = {}; end; if nargin<2, type = []; end; if nargin<3, subtype = []; end; if nargin<4, objId = []; end; %create a new label label = struct('points',points, 'type',type, ... 'subtype',subtype, 'obj',objId); end function nl = nLabels(ld, frameIdx) % NLABELS gets the number of labels in the required frame % % INPUTS % ------ % ld - the input label data % frameIdx - the frame index % % OUTPUTS % ------- % nl - the number of labels % nl = length(ld.frames(frameIdx).labels); end function [ld, lblIdx] = addLabel(ld, frameIdx, points, type, subtype, objId) % ADDLABEL adds a new label % % INPUTS % ------ % ld - the input label data % frameIdx - the frame index % points - the points for that label or the label structure if given % type - the type of label % subtype - the subtype of the label % objId - the objId of the label % % OUTPUTS % ------- % ld - the output updated label data % lblIdx - the new label index % if nargin<3, points = []; end; if nargin<4, type = []; end; if nargin<5, subtype = []; end; if nargin<6, objId = []; end; %get the new label index lblIdx = nLabels(ld, frameIdx) + 1; %create the new label if not a struct if isstruct(points), label = points; else label = createLabel(points, type, subtype, objId); end; %add the label to the required frame ld.frames(frameIdx).labels(lblIdx) = label; end function ld = updateLabel(ld, frameIdx, lblIdx, points, type, subtype, objId) % UPDATELABEL updates an existing label % % INPUTS % ------ % ld - the input label data % frameIdx - the frame id % lblIdx - the index of the label to change % points - the points for that label (don't change if nan). It can also % be a structure, in which case it is a label structure, % so just replace it % type - the type of label (don't change if nan) % subtype - the subtype of the label (don't change if nan) % objId - the objId of the label (don't change if nan) % % OUTPUTS % ------- % ld - the output updated label data % %check if just to replace it if nargin>=4 && isstruct(points) label = points; %we are passaed in independent components of the labels else %get the label label = ld.frames(frameIdx).labels(lblIdx); %update the label if nargin>=7 && ~any(isnan(objId)), label.obj = objId; end; if nargin>=6 && ~any(isnan(subtype)), label.subtype = subtype; end; if nargin>=5 && ~any(isnan(type)), label.type = type ; end; if nargin>=4 && ~any(any(isnan(points))), label.points = points; end; end; %put it back ld.frames(frameIdx).labels(lblIdx) = label; end function label = getLabel(ld, frameIdx, lblIdx) % GETLABEL retuns the required label % % INPUTS % ------ % ld - the input label data % frameIdx - the frame index % lblIdx - the index of the label to return. If empty or absent, then % return the labels in this frame % % OUTPUTS % ------- % label - the returned label(s), which is a structure with fields % .points - the label points % .type - the label type % .subtype - the label subtype % .obj - the label object id % %get the label if nargin<3 || isempty(lblIdx) lblIdx = 1:length(ld.frames(frameIdx).labels); end; %return label = ld.frames(frameIdx).labels(lblIdx); end function ld = removeLabel(ld, frameIdx, lblIdx) % REMOVELABEL removes a label % % INPUTS % ------ % ld - the input label data % frameIdx - the frame id % lblIdx - the index of the label to remove % % OUTPUTS % ------- % ld - the output updated label data % %remove the label ld.frames(frameIdx).labels(lblIdx) = []; end
github
VIP-Group/DBP-master
DBP_detector_sim.m
.m
DBP-master/uplink/DBP_detector_sim.m
13,321
utf_8
15048a8d5848729bdbfbb43738f311f9
% ========================================================================= % Decentralized UPLINK simulator for the paper % "Decentralized Baseband Processing for Massive MU-MIMO Systems" % ------------------------------------------------------------------------- % Revision history: % % - aug-13-2017 v0.1 cs: simplified and commented code for GitHub % % ------------------------------------------------------------------------- % (c) 2017 Christoph Studer; e-mail: [email protected] % ------------------------------------------------------------------------- % If you are using the simulator (or parts of it) for a publication, then % you MUST cite our paper: % % K. Li, R. Sharan, Y. Chen, T. Goldstein, J. R. Cavallaro, and C. Studer, % "Decentralized Baseband Processing for Massive MU-MIMO Systems", % IEEE J. Emerging and Sel. Topics in Circuits and Systems (JETCAS) % to appear in 2017 % % and clearly mention this in your paper. %========================================================================= function res = DBP_detector_sim(varargin) % -- set up default/custom parameters if isempty(varargin) disp('using default simulation settings and parameters...') % set default simulation parameters par.runID = 0; % simulation ID (used to reproduce results) par.B = 128; % receive antennas par.U = 8; % transmit antennas (set not larger than MR!) par.mod = '16QAM'; % modulation type: 'BPSK','QPSK','16QAM','64QAM' par.trials = 1000; % number of Monte-Carlo trials (transmissions) par.SNRdB_list = -4:4:16; % list of SNR [dB] values to be simulated % select data detector to be used % centralized : `ZF`, `uMMSE', 'SIMO' % decentralized : CG-based `DUCG_ZF`, `DUCG_MMSE` % ADMM-based 'DZF', `DMMSE', 'DBOX' par.detector = 'DMMSE'; par.vers = 'SxS2'; % inverse: 'UxU1', 'SxS1', 'SxS2' (only for ADMM) par.CHEST = 'on'; % channel estimation errors 'on' or 'off' par.plot = 'on'; % plot results? 'on' or 'off' par.save = 'on'; % save results? 'on' or 'off' % parameters for DBP (see paper) par.C = 8; % number of clusters par.maxiter = 5; % maximum algorithm iterations (for CG and ADMM) par.rho = 7; % tuning parameter: regularizer (only for ADMM) par.gamma = 2; % tuning parameters: step size (only for ADMM) % else disp('use custom simulation settings and parameters...') par = varargin{1}; % only argument is par structure end % -- initialization % use runId random seed (enables reproducibility) rng(par.runID); % generate reasonable filename par.simName = ['ERR_UL_' num2str(par.B) 'x' num2str(par.U) '_' par.mod '_' par.detector '_rho' num2str(par.rho) '_gamma' num2str(par.gamma) ]; % simulation name (used for saving results) % set up Gray-mapped constellation alphabet (according to IEEE 802.11) switch (par.mod) case 'BPSK', par.symbols = [ -1 1 ]; case 'QPSK', par.symbols = [ -1-1i,-1+1i, ... +1-1i,+1+1i ]; case '16QAM', par.symbols = [ -3-3i,-3-1i,-3+3i,-3+1i, ... -1-3i,-1-1i,-1+3i,-1+1i, ... +3-3i,+3-1i,+3+3i,+3+1i, ... +1-3i,+1-1i,+1+3i,+1+1i ]; case '64QAM', par.symbols = [ -7-7i,-7-5i,-7-1i,-7-3i,-7+7i,-7+5i,-7+1i,-7+3i, ... -5-7i,-5-5i,-5-1i,-5-3i,-5+7i,-5+5i,-5+1i,-5+3i, ... -1-7i,-1-5i,-1-1i,-1-3i,-1+7i,-1+5i,-1+1i,-1+3i, ... -3-7i,-3-5i,-3-1i,-3-3i,-3+7i,-3+5i,-3+1i,-3+3i, ... +7-7i,+7-5i,+7-1i,+7-3i,+7+7i,+7+5i,+7+1i,+7+3i, ... +5-7i,+5-5i,+5-1i,+5-3i,+5+7i,+5+5i,+5+1i,+5+3i, ... +1-7i,+1-5i,+1-1i,+1-3i,+1+7i,+1+5i,+1+1i,+1+3i, ... +3-7i,+3-5i,+3-1i,+3-3i,+3+7i,+3+5i,+3+1i,+3+3i ]; end % extract average symbol energy par.Es = mean(abs(par.symbols).^2); % precompute bit labels par.Q = log2(length(par.symbols)); % number of bits per symbol par.bits = de2bi(0:length(par.symbols)-1,par.Q,'left-msb'); % track simulation time time_elapsed = 0; % -- start simulation % initialize result arrays (detector x SNR) switch (par.detector) case {'DZF','DMMSE','DBOX','DUCG_MMSE','DUCG_ZF'} par.distr = 1; otherwise par.distr = 0; par.maxiter = 1; end res.par = par; % store param array res.VER = zeros(par.maxiter,length(par.SNRdB_list)); % vector error rate res.SER = zeros(par.maxiter,length(par.SNRdB_list)); % symbol error rate res.BER = zeros(par.maxiter,length(par.SNRdB_list)); % bit error rate % generate random bit stream (antenna x bit x trial) bits = randi([0 1],par.U,par.Q,par.trials); %initialize parameters for ADMM % trials loop disp('run simulation...') tic for t=1:par.trials % generate transmit symbol idx = bi2de(bits(:,:,t),'left-msb')+1; s = par.symbols(idx).'; % generate iid Gaussian channel matrix & noise vector n = sqrt(0.5)*(randn(par.B,1)+1i*randn(par.B,1)); H = sqrt(0.5)*(randn(par.B,par.U)+1i*randn(par.B,par.U)); NH = sqrt(0.5)*(randn(par.B,par.U)+1i*randn(par.B,par.U)); % used for CHEST % transmit over noiseless channel (will be used later) x = H*s; % SNR loop for k=1:length(par.SNRdB_list) % compute noise variance (average SNR per receive antenna is: SNR=MT*Es/N0) N0 = par.U*par.Es*10^(-par.SNRdB_list(k)/10); % transmit data over noisy channel y = x+sqrt(N0)*n; % model channel estimation errors (CHEST) switch (par.CHEST) case 'on' Hest = H + sqrt(N0/par.U/par.Es)*NH; % errors proportional to SNR otherwise % assume perfect CSI Hest = H; end % select algorithms switch (par.detector) case 'ZF', % zero-forcing detection [idxhat,bithat] = ZF(par,Hest,y); case 'MMSE', % unbiased MMSE detector [idxhat,bithat] = MMSE(par,Hest,y,N0); case 'SIMO', % SIMO lower bound [idxhat,bithat] = SIMO(par,Hest,y,s); % also pass true signal case {'DUCG_MMSE','DUCG_ZF'} % conjuage gradients [idxhat,bithat] = DUCG(par,Hest,y,N0); case {'DZF','DMMSE','DBOX'} % ADMM based method [idxhat,bithat] = DU(par,Hest,y,N0); otherwise, error('par.detector type not defined.') end % -- compute error metrics for l = 1:size(idxhat,2) [VER,SER,BER] = getError(par,idxhat(:,l),bithat(:,:,l),idx,bits(:,:,t)); res.VER(l,k) = res.VER(l,k) + VER; res.SER(l,k) = res.SER(l,k) + SER; res.BER(l,k) = res.BER(l,k) + BER; end end % SNR loop % keep track of simulation time if toc>10 time=toc; time_elapsed = time_elapsed + time; fprintf('estimated remaining simulation time: %3.0f min.\n',time_elapsed*(par.trials/t-1)/60); tic end end % trials loop % -- normalize results res.VER = res.VER/par.trials; res.SER = res.SER/par.trials; res.BER = res.BER/par.trials; res.time_elapsed = time_elapsed + toc; % -- save final results (par and res structure) if strcmp(par.save,'on') if ~exist('results','dir') mkdir results end save([ 'results' filesep par.simName ],'res'); end % -- show results (generates fairly nice Matlab plot) if strcmp(par.plot,'on') marker_style = {'bo-','rs--','mv-.','kp:','g*-','c>--','yx:'}; plot_list = unique(round(logspace(0,log10(par.maxiter),7))); figure(1) for d=1:length(plot_list) if d==1 semilogy(par.SNRdB_list,res.BER(d,:),marker_style{d},'LineWidth',2) hold on else semilogy(par.SNRdB_list,res.BER(d,:),marker_style{d},'LineWidth',2) end end hold off grid on xlabel('average SNR per receive antenna [dB]','FontSize',12) ylabel('uncoded bit error rate (BER)','FontSize',12) axis([min(par.SNRdB_list) max(par.SNRdB_list) 1e-4 1]) if par.distr l = cell(1,length(plot_list)); for i = 1:length(plot_list) l{i} = ['Iteration ' num2str(plot_list(i))]; end legend(l,'Fontsize',18) end set(gca,'FontSize',12) end end % -- data detector functions %% zero-forcing (ZF) detector function [idxhat,bithat] = ZF(par,H,y) xhat = H\y; [~,idxhat] = min(abs(xhat*ones(1,length(par.symbols))-ones(par.U,1)*par.symbols).^2,[],2); bithat = par.bits(idxhat,:); end %% unbiased MMSE detector (MMSE) function [idxhat,bithat] = MMSE(par,H,y,N0) W = (H'*H+(N0/par.Es)*eye(par.U))\(H'); xhat = W*y; G = real(diag(W*H)); [~,idxhat] = min(abs(xhat*ones(1,length(par.symbols))-G*par.symbols).^2,[],2); bithat = par.bits(idxhat,:); end %% SIMO lower bound function [idxhat,bithat] = SIMO(par,Hest,y,sTrue) y_tilde = y-Hest*sTrue; % -- MMSE detection main loop for n=1:par.U % interference cancellation (with known data) y_SIMO = y_tilde + Hest(:,n)*sTrue(n); % do optimal SIMO detection for interference-free system xhat(n,1) = Hest(:,n)'*y_SIMO/norm(Hest(:,n),2)^2; end [~,idxhat] = min(abs(xhat*ones(1,length(par.symbols))-ones(par.U,1)*par.symbols).^2,[],2); bithat = par.bits(idxhat,:); end %% find nearest neighbors function [idxhat,bithat] = getEstimate(par,xhat) [~,idxhat] = min(abs(xhat*ones(1,length(par.symbols))-ones(par.U,1)*par.symbols).^2,[],2); bithat = par.bits(idxhat,:); end %% get error function [VER,SER,BER] = getError(par,idxhat,bithat,idx,bits) err = (idx~=idxhat); VER = any(err); SER = sum(err)/par.U; BER = sum(sum(bits~=bithat))/(par.U*par.Q); end %% ADMM-based decentralized uplink detectors function [idxhat,bithat] = DU(par,H,y,N0) idxhat = zeros(par.U,par.maxiter); bithat = zeros(par.U,par.Q,par.maxiter); lambda = zeros(par.U,par.C); z_c = zeros(par.U,par.C); s = zeros(par.U,1); S = par.B/par.C; switch (par.detector) case 'DMMSE' reg = par.C+N0/(par.Es*par.rho); otherwise % Do not regularize for ZF and BOX reg = par.C; end % -- preprocessing for c=1:par.C H_c(:,:,c) = H(S*(c-1)+1:S*c,:); %get the appropriate part of H y_c = y(S*(c-1)+1:S*c); switch (par.vers) case 'SxS1' Ainv(:,:,c) = inv(H_c(:,:,c)*H_c(:,:,c)'+eye(S)*par.rho); y_reg(:,c) = H_c(:,:,c)'*(Ainv(:,:,c)*y_c); case 'SxS2' Ainv(:,:,c) = inv(H_c(:,:,c)*H_c(:,:,c)'+eye(S)*par.rho); Gtmp = H_c(:,:,c)'*Ainv(:,:,c); y_reg(:,c) = Gtmp*y_c; G(:,:,c) = Gtmp*H_c(:,:,c); case 'UxU1' Binv(:,:,c) = inv(H_c(:,:,c)'*H_c(:,:,c)+eye(par.U)*par.rho); y_reg(:,c) = Binv(:,:,c)*(H_c(:,:,c)'*y_c); otherwise error('par.vers not defined') end end % -- detection loop for l = 1:par.maxiter for c = 1:par.C %local minimization step switch (par.vers) case 'SxS1' z_c(:,c) = y_reg(:,c) + ( (s - lambda(:,c)) - H_c(:,:,c)'*(Ainv(:,:,c)*(H_c(:,:,c)*(s - lambda(:,c)))) ); case 'SxS2' z_c(:,c) = y_reg(:,c) + ( (s - lambda(:,c)) - G(:,:,c)*(s - lambda(:,c))) ; case 'UxU1' z_c(:,c) = y_reg(:,c) + par.rho*(Binv(:,:,c)*(s - lambda(:,c))); end end switch (par.detector) case 'DBOX' s = sum((z_c + lambda),2)/(reg); %global averaging step s = projinf(par,s,max(real(par.symbols))); % experimental box regularizer otherwise s = sum((z_c + lambda),2)/(reg); %global averaging step end % update lagrange multiplier for c = 1:par.C lambda(:,c) = lambda(:,c) + par.gamma*(z_c(:,c) - s); end [idxhat(:,l),bithat(:,:,l)] = getEstimate(par,s); end end % project onto alpha infinity-tilde-norm ball function sproj = projinf(par,s,alpha) sr = real(s); idxr = abs(sr)>alpha; sr(idxr) = sign(sr(idxr))*alpha; si = imag(s); idxi = abs(si)>alpha; si(idxi) = sign(si(idxi))*alpha; if strcmp(par.mod,'BPSK') sproj = sr; else sproj = sr + 1i*si; end end % ADMM methods %% decentralized uplink via decentralized CG function [idxhat,bithat] = DUCG(par,H,y,N0) % initialization S = par.B/par.C; H_c = zeros(S,par.U,par.C); yMRC_c = zeros(par.U,par.C); % distributed preprocessing (iteration 1) for c=1:par.C H_c(:,:,c) = H(S*(c-1)+1:S*c,:); % get the appropriate part of H yMRC_c(:,c) = H_c(:,:,c)'*y(S*(c-1)+1:S*c); % compute local MRC end % centralized processing r = sum(yMRC_c,2); % sum row-wise p = r ; rsold = r'*r; x = zeros(par.U,1); Ap_c = zeros(par.U,par.C); % inner loop = equalization stage (iterations 2,3,...) for l=1:par.maxiter % decentralized matrix processing for c=1:par.C Ap_c(:,c) = H_c(:,:,c)'*(H_c(:,:,c)*p); end % centralized processing (MMSE) switch par.detector case 'DUCG_MMSE' Ap = sum(Ap_c,2) + (N0/par.Es)*p; case 'DUCG_ZF' Ap = sum(Ap_c,2); end % conventional CG updates alpha = rsold/(p'*Ap); x = x + alpha*p; r = r - alpha*Ap; rsnew = r'*r; p = r + (rsnew/rsold)*p; rsold = rsnew; % get estimates [idxhat(:,l),bithat(:,:,l)] = getEstimate(par,x); end end % DUCG
github
VIP-Group/DBP-master
DBP_precoder_sim.m
.m
DBP-master/downlink/DBP_precoder_sim.m
10,550
utf_8
1ee2ead02cd6045fb55ef5a1f4b75d1b
% ========================================================================= % Decentralized DOWNLINK simulator for the paper % "Decentralized Baseband Processing for Massive MU-MIMO Systems" % ------------------------------------------------------------------------- % Revision history: % % - aug-13-2017 v0.1 cs: simplified and commented code for GitHub % % ------------------------------------------------------------------------- % (c) 2017 Christoph Studer; e-mail: [email protected] % ------------------------------------------------------------------------- % If you are using the simulator (or parts of it) for a publication, then % you MUST cite our paper: % % K. Li, R. Sharan, Y. Chen, T. Goldstein, J. R. Cavallaro, and C. Studer, % "Decentralized Baseband Processing for Massive MU-MIMO Systems", % IEEE J. Emerging and Sel. Topics in Circuits and Systems (JETCAS) % to appear in 2017 % % and clearly mention this in your paper. %========================================================================= function res = DBP_precoder_sim(varargin) % -- set up default/custom parameters if isempty(varargin) disp('using default simulation settings and parameters...') % set default simulation parameters par.runId = 0; % simulation ID (used to reproduce results) par.U = 8; % user antennas par.B = 128; % BS antennas par.mod = '16QAM'; % modulation type: 'BPSK','QPSK','16QAM','64QAM' par.trials = 1000; % number of Monte-Carlo trials (transmissions) par.SNRdB_list = 0:4:20; % list of SNR [dB] values to be simulated % select precoder to be used % centralized : `ZF`, `MRC' % decentralized : 'DP' as described in Algorithm 3 par.precoder = 'DP'; % select precoder scheme 'MRC', '' par.CHEST = 'on'; % channel estimation 'on' or 'off' par.plot = 'on'; % plot results 'on' or 'off' par.save = 'on'; % save results: 'on' or 'off' % parameters for DBP (see paper) par.C = 8; % number of clusters par.vers = 'SxS1'; % inverse: 'UxU1' or 'SxS1' or 'UxU2' or 'SxS2' par.maxiter = 5; % maximum algorithm iterations par.rho = 1; % tuning parameter: regularizer (only for ADMM) par.gamma = 1; % tuning parameters: step size (only for ADMM) par.epsilon = 0.0; % precoder accuracy (0 = ZF precoding) else disp('use custom simulation settings and parameters...') par = varargin{1}; % only argument is par structure end % -- initialization % use runId random seed (enables reproducibility) rng(par.runId); % generate reasonable filename par.simName = ['ERR_DL_' num2str(par.B) 'x' num2str(par.U) '_' par.mod '_' par.precoder '_rho' num2str(par.rho) '_gamma' num2str(par.gamma) ]; % simulation name (used for saving results) % set up Gray-mapped constellation alphabet (according to IEEE 802.11) switch (par.mod) case 'BPSK', par.symbols = [ -1 1 ]; case 'QPSK', par.symbols = [ -1-1i,-1+1i, ... +1-1i,+1+1i ]; case '16QAM', par.symbols = [ -3-3i,-3-1i,-3+3i,-3+1i, ... -1-3i,-1-1i,-1+3i,-1+1i, ... +3-3i,+3-1i,+3+3i,+3+1i, ... +1-3i,+1-1i,+1+3i,+1+1i ]; case '64QAM', par.symbols = [ -7-7i,-7-5i,-7-1i,-7-3i,-7+7i,-7+5i,-7+1i,-7+3i, ... -5-7i,-5-5i,-5-1i,-5-3i,-5+7i,-5+5i,-5+1i,-5+3i, ... -1-7i,-1-5i,-1-1i,-1-3i,-1+7i,-1+5i,-1+1i,-1+3i, ... -3-7i,-3-5i,-3-1i,-3-3i,-3+7i,-3+5i,-3+1i,-3+3i, ... +7-7i,+7-5i,+7-1i,+7-3i,+7+7i,+7+5i,+7+1i,+7+3i, ... +5-7i,+5-5i,+5-1i,+5-3i,+5+7i,+5+5i,+5+1i,+5+3i, ... +1-7i,+1-5i,+1-1i,+1-3i,+1+7i,+1+5i,+1+1i,+1+3i, ... +3-7i,+3-5i,+3-1i,+3-3i,+3+7i,+3+5i,+3+1i,+3+3i ]; end % extract average symbol energy par.Es = mean(abs(par.symbols).^2); % normalize so that transmit vector s has unit norm par.symbols = par.symbols/sqrt(mean(abs(par.symbols).^2))/sqrt(par.U); % precompute bit labels par.Q = log2(length(par.symbols)); % number of bits per symbol par.bits = de2bi(0:length(par.symbols)-1,par.Q,'left-msb'); % track simulation time time_elapsed = 0; % -- start simulation % extract cluster size par.S = par.B/par.C; % cluster size % initialize result arrays (detector x SNR) if ~strcmp(par.precoder,'DP') par.maxiter = 1; par.distr = 0; else par.distr = 1; end res.par = par; % save parameter structure res.VER = zeros(par.maxiter,length(par.SNRdB_list)); % vector error rate res.SER = zeros(par.maxiter,length(par.SNRdB_list)); % symbol error rate res.BER = zeros(par.maxiter,length(par.SNRdB_list)); % bit error rate % generate random bit stream (antenna x bit x trial) bits = randi([0 1],par.U,par.Q,par.trials); % trials loop tic for t=1:par.trials % generate transmit symbol idx = bi2de(bits(:,:,t),'left-msb')+1; s = par.symbols(idx).'; % create unit-norm transmit vector % generate iid Gaussian channel matrix & noise vector n = sqrt(0.5)*(randn(par.U,1)+1i*randn(par.U,1)); H = sqrt(0.5)*(randn(par.U,par.B)+1i*randn(par.U,par.B)); NH = sqrt(0.5)*(randn(par.U,par.B)+1i*randn(par.U,par.B)); % used for CHEST % TX side processing switch (par.precoder) case 'ZF' % ZF beamforming x = pinv(H)*s; case 'MRC' % MRC beamforming x = H'*(s./sum(abs(H).^2,2)); case 'DP' % decentralized precoding x = DP(par,H,s); otherwise, error('par.precoder type not defined.') end % SNR loop for k=1:length(par.SNRdB_list) % iteration loop for l = 1:par.maxiter par.Ex = norm(x(:,l),2)^2; % compute noise variance (average SNR per receive antenna is: SNR=MT*Es/N0) N0 = par.Ex*10^(-par.SNRdB_list(k)/10); % channel estimation (CHEST) switch (par.CHEST) case 'on' Hest = H + sqrt(N0/par.Ex)*NH; % error happens in uplink otherwise % assume perfect CHEST Hest = H; end % transmit over noiseless channel Hx = Hest*x(:,l); % transmit data over noisy channel y = Hx+sqrt(N0)*n; [~,idxhat] = min(abs(y*ones(1,length(par.symbols))-ones(par.U,1)*par.symbols).^2,[],2); bithat = par.bits(idxhat,:); % -- compute error and complexity metrics err = (idx~=idxhat); res.VER(l,k) = res.VER(l,k) + any(err); res.SER(l,k) = res.SER(l,k) + sum(err)/par.U; res.BER(l,k) = res.BER(l,k) + sum(sum(bits(:,:,t)~=bithat))/(par.U*par.Q); end % iteration loop end % SNR loop % keep track of simulation time if toc>10 time=toc; time_elapsed = time_elapsed + time; fprintf('estimated remaining simulation time: %3.0f min.\n',time_elapsed*(par.trials/t-1)/60); tic end end % trials loop % normalize results res.VER = res.VER/par.trials; res.SER = res.SER/par.trials; res.BER = res.BER/par.trials; res.time_elapsed = time_elapsed + toc; % -- save final results (res structure) if strcmp(par.save,'on') if ~exist('results','dir') mkdir results end save([ 'results' filesep par.simName ],'res'); end % -- show results (generates fairly nice Matlab plot) if strcmp(par.plot,'on') marker_style = {'bo-','rs--','mv-.','kp:','g*-','c>--','yx:'}; h=figure(1); plot_list = unique(round(logspace(0,log10(par.maxiter),7))); for d=1:length(plot_list) if d==1 semilogy(par.SNRdB_list,res.SER(plot_list(d),:),marker_style{d},'LineWidth',2) hold on else semilogy(par.SNRdB_list,res.SER(plot_list(d),:),marker_style{d},'LineWidth',2) end end hold off grid on xlabel('average SNR per receive antenna [dB]','FontSize',12) ylabel('uncoded symbol error rate (SER)','FontSize',12) axis([min(par.SNRdB_list) max(par.SNRdB_list) 1e-4 1]) if par.distr l = cell(1,length(plot_list)); for i = 1:length(plot_list) l{i} = ['Iteration ' num2str(plot_list(i))]; end legend(l,'Fontsize',18) end set(gca,'FontSize',12) end end %% decentralized precoder function [x] = DP(par,H,s) % -- initialize x = zeros(par.B,par.maxiter); % output, each column corresponds to one iteration lambda_c = zeros(par.U,par.C); x_c = zeros(par.S,par.C); w_c = zeros(par.U,par.C); Hx_c = zeros(par.U,par.C); H_c = zeros(par.U,par.S,par.C); % important for fast convergence (reasonable initial guess) z_c = max(par.U/par.B,1/par.C)*s*ones(1,par.C); % -- preprocessing for c=1:par.C H_c(:,:,c) = H(:,par.S*(c-1)+1:par.S*c); % get the appropriate part of H switch par.vers case 'SxS1' Ainv(:,:,c) = (H_c(:,:,c)'*H_c(:,:,c) + (1/par.rho)*eye(par.S))\(H_c(:,:,c)'); % SxS inverse case 'SxS2' Ainv(:,:,c) = inv(H_c(:,:,c)'*H_c(:,:,c) + (1/par.rho)*eye(par.S)); % SxS inverse case 'UxU1' Binv(:,:,c) = H_c(:,:,c)'/(H_c(:,:,c)*H_c(:,:,c)' + (1/par.rho)*eye(par.U)); % UxU inverse case 'UxU2' Binv(:,:,c) = inv(H_c(:,:,c)*H_c(:,:,c)' + (1/par.rho)*eye(par.U)); % UxU inverse otherwise error('mode not defined') end end % -- start iteration for l = 1:par.maxiter % cluster-wise equalization for c=1:par.C switch par.vers case 'SxS1' x_c(:,c) = Ainv(:,:,c)*(z_c(:,c) + lambda_c(:,c)); % SxS inverse case 'SxS2' x_c(:,c) = Ainv(:,:,c)*(H_c(:,:,c)'*(z_c(:,c) + lambda_c(:,c))); % SxS inverse case 'UxU1' x_c(:,c) = Binv(:,:,c)*(z_c(:,c) + lambda_c(:,c)); % UxU inverse case 'UxU2' x_c(:,c) = H_c(:,:,c)'*(Binv(:,:,c)*(z_c(:,c) + lambda_c(:,c))); % UxU inverse otherwise error('mode not defined') end Hx_c(:,c) = H_c(:,:,c)*x_c(:,c); w_c(:,c) = Hx_c(:,c)-lambda_c(:,c); end % consensus step w_avg = s-sum(w_c,2); w_norm = norm(w_avg,2); w_avg = (max(0,1-par.epsilon/w_norm)*1/par.C)*w_avg; % projection % cluster-wise update for c=1:par.C z_c(:,c) = w_c(:,c)+w_avg; lambda_c(:,c) = lambda_c(:,c) - par.gamma*(Hx_c(:,c)-z_c(:,c)); end x(:,l) = x_c(:); % vectorize output end end
github
athakapo/Continuously-Informed-Heuristic-A---Optimal-path-retrieval-inside-an-unknown-environment-master
Continuously_Informed_Astar.m
.m
Continuously-Informed-Heuristic-A---Optimal-path-retrieval-inside-an-unknown-environment-master/Continuously_Informed_Astar.m
26,747
utf_8
5d783088f424b821356b527dd8560e48
function varargout = Continuously_Informed_Astar(varargin) % CONTINUOUSLY_INFORMED_ASTAR MATLAB code for Continuously_Informed_Astar.fig % CONTINUOUSLY_INFORMED_ASTAR, by itself, creates a new CONTINUOUSLY_INFORMED_ASTAR or raises the existing % singleton*. % % H = CONTINUOUSLY_INFORMED_ASTAR returns the handle to a new CONTINUOUSLY_INFORMED_ASTAR or the handle to % the existing singleton*. % % CONTINUOUSLY_INFORMED_ASTAR('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CONTINUOUSLY_INFORMED_ASTAR.M with the given input arguments. % % CONTINUOUSLY_INFORMED_ASTAR('Property','Value',...) creates a new CONTINUOUSLY_INFORMED_ASTAR or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Continuously_Informed_Astar_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Continuously_Informed_Astar_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 Continuously_Informed_Astar % Last Modified by GUIDE v2.5 01-Sep-2017 00:02:17 % Begin initialization code - DO NOT EDIT addpath('matlabFunctions') gui_Singleton = 0; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Continuously_Informed_Astar_OpeningFcn, ... 'gui_OutputFcn', @Continuously_Informed_Astar_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 Continuously_Informed_Astar is made visible. function Continuously_Informed_Astar_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 Continuously_Informed_Astar (see VARARGIN) % Choose default command line output for Continuously_Informed_Astar handles.weightDefaultValue = 1.2; handles.output = hObject; %handles.ValidExperimntSetUp = 0; handles.times=0; handles.stop_now = 0; set(handles.save_button,'Enable','off') set(handles.abort_button,'Enable','off') set(handles.start_button,'Enable','off') set(handles.submit_button,'Enable','on') set(handles.weight,'Enable','off') set(handles.weight,'String',handles.weightDefaultValue) s = sprintf('Button tooltip line 1\nButton tooltip line 2'); set(handles.text19,'TooltipString', ['<100 and >2']) set(handles.text20,'TooltipString', ['<70% of the total cells']) set(handles.submit_button,'TooltipString', ['Also, renew the obstacles'' locations']) %set(gcf,'pos',[10 10 200 50]) %set(handles.methodgroup,'SelectionChangeFcn',@methodgroup_SelectionChangeFcn); % Update handles structure guidata(hObject, handles); % UIWAIT makes Continuously_Informed_Astar wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = Continuously_Informed_Astar_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 start_button. function start_button_Callback(hObject, eventdata, handles) % hObject handle to start_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)\ weight=handles.weightDefaultValue; if (handles.times==1) cla(handles.axes1,'reset'); disable(hObject, eventdata, handles); handles=InitializeMainAxes(handles,handles.SIMULparam.gridT,... handles.SIMULparam.goalCells,handles.SIMULparam.robotInitPos,... handles.SIMULparam.rows,handles.SIMULparam.cols,handles.SIMULparam.sizeCell,... handles.SIMULparam.pauseTime); end u = get(get(handles.methodgroup,'SelectedObject'),'Tag'); switch u case 'CIA_button' alg=9; case 'A_button' alg=1; case 'weigted_button' weight=str2num(get(handles.weight,'String')); alg=8; otherwise alg=0; end disable(hObject, eventdata, handles); set(handles.abort_button,'Enable','on') algorithm_call(alg,weight,hObject,handles) set(handles.abort_button,'Enable','off') enable(hObject, eventdata, handles); handles.times=1; guidata(hObject, handles); % --- Executes on button press in save_button. function save_button_Callback(hObject, eventdata, handles) % hObject handle to save_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) gridT=handles.SIMULparam.gridT; ob=size(handles.SIMULparam.obstacles,1); goalCells=handles.SIMULparam.goalCells; robotInitPos=handles.SIMULparam.robotInitPos; sizeCell=handles.SIMULparam.sizeCell; rows=handles.SIMULparam.rows; cols=handles.SIMULparam.cols; obstacles=handles.SIMULparam.obstacles; uisave({'gridT','goalCells','robotInitPos','sizeCell','rows','cols','ob',... 'obstacles'},strcat('Experiment_',num2str(cols),'x',num2str(rows),'_',num2str(ob),'_obstacles')) guidata(hObject, handles); function weight_Callback(hObject, eventdata, handles) % hObject handle to weight (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 weight as text % str2double(get(hObject,'String')) returns contents of weight as a double weight=str2num(get(handles.weight,'String')); if isempty(weight) set(handles.weight,'ForegroundColor','red') set(handles.start_button,'Enable','off') else set(handles.weight,'ForegroundColor','black') if strcmp(get(handles.submit_button, 'Enable'),'on') && strcmp(get(handles.save_button, 'Enable'),'on') set(handles.start_button,'Enable','on') end end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function weight_CreateFcn(hObject, eventdata, handles) % hObject handle to weight (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 button press in load_button. function load_button_Callback(hObject, eventdata, handles) % hObject handle to load_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.x_goal,'ForegroundColor','black') set(handles.y_goal,'ForegroundColor','black') set(handles.x_start,'ForegroundColor','black') set(handles.y_start,'ForegroundColor','black') set(handles.rows_size,'ForegroundColor','black') set(handles.columns_size,'ForegroundColor','black') set(handles.num_ob,'ForegroundColor','black') cla(handles.axes1,'reset'); handles.times=0; [filename pathname]=uigetfile({'*.mat','File Selector'}); fullpathname = strcat(pathname,filename); handles.file_name=fullpathname; load(fullpathname) set(handles.rows_size,'String',num2str(cols)) set(handles.columns_size,'String',num2str(rows)) set(handles.x_start,'String',num2str(robotInitPos(2))) set(handles.y_start,'String',num2str(robotInitPos(1))) set(handles.x_goal,'String',num2str(goalCells(2))) set(handles.y_goal,'String',num2str(goalCells(1))) set(handles.num_ob,'String',strcat(num2str(ob))) if ValidEnviromentalParameters(hObject, eventdata, handles) disable(hObject, eventdata, handles); handles = main(0,0,0,0,0,0,0,fullpathname,handles); enable(hObject, eventdata, handles); set(handles.save_button,'Enable','off') end guidata(hObject, handles); function rows_size_Callback(hObject, eventdata, handles) % hObject handle to rows_size (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 rows_size as text % str2double(get(hObject,'String')) returns contents of rows_size as a double ValidEnviromentalParameters(hObject, eventdata, handles); guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function rows_size_CreateFcn(hObject, eventdata, handles) % hObject handle to rows_size (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 num_ob_Callback(hObject, eventdata, handles) % hObject handle to num_ob (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 num_ob as text % str2double(get(hObject,'String')) returns contents of num_ob as a double ValidEnviromentalParameters(hObject, eventdata, handles); guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function num_ob_CreateFcn(hObject, eventdata, handles) % hObject handle to num_ob (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 edit9_Callback(hObject, eventdata, handles) % hObject handle to robot_start (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 robot_start as text % str2double(get(hObject,'String')) returns contents of robot_start as a double % --- Executes during object creation, after setting all properties. function edit9_CreateFcn(hObject, eventdata, handles) % hObject handle to robot_start (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 edit10_Callback(hObject, eventdata, handles) % hObject handle to robot_goal (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 robot_goal as text % str2double(get(hObject,'String')) returns contents of robot_goal as a double % --- Executes during object creation, after setting all properties. function edit10_CreateFcn(hObject, eventdata, handles) % hObject handle to robot_goal (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 edit11_Callback(hObject, eventdata, handles) % hObject handle to rows_size (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 rows_size as text % str2double(get(hObject,'String')) returns contents of rows_size as a double % --- Executes during object creation, after setting all properties. function edit11_CreateFcn(hObject, eventdata, handles) % hObject handle to rows_size (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 edit12_Callback(hObject, eventdata, handles) % hObject handle to num_ob (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 num_ob as text % str2double(get(hObject,'String')) returns contents of num_ob as a double % --- Executes during object creation, after setting all properties. function edit12_CreateFcn(hObject, eventdata, handles) % hObject handle to num_ob (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 button press in submit_butto function submit_button_Callback(hObject, eventdata,handles) % hObject handle to submit_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles = guidata(hObject); cla(handles.axes1,'reset'); handles.times=0; full_map=''; x_size=str2num(get(handles.rows_size,'String')); y_size = str2num(get(handles.columns_size,'String')); x_s = str2num(get(handles.x_start,'String')); y_s = str2num(get(handles.y_start,'String')); x_g = str2num(get(handles.x_goal,'String')); y_g = str2num(get(handles.y_goal,'String')); num_obstacles=str2num(get(handles.num_ob,'String')); disable(hObject, eventdata, handles); handles = main(x_size,y_size,x_s,y_s,x_g,y_g,num_obstacles,full_map,handles); enable(hObject, eventdata, handles); %handles.ValidExperimntSetUp = 1; %set(handles.save_button,'Enable','on') guidata(hObject, handles); function enable(hObject, eventdata, handles) set(handles.load_button,'Enable','on') set(handles.submit_button,'Enable','on') set(handles.save_button,'Enable','on') set(handles.start_button,'Enable','on') set(handles.rows_size,'Enable','on') set(handles.columns_size,'Enable','on') set(handles.x_start,'Enable','on') set(handles.y_start,'Enable','on') set(handles.x_goal,'Enable','on') set(handles.y_goal,'Enable','on') set(handles.num_ob,'Enable','on') set(handles.CIA_button,'Enable','on') set(handles.A_button,'Enable','on') set(handles.weigted_button,'Enable','on') %set(handles.weight,'Enable','on') function disable(hObject, eventdata, handles) set(handles.load_button,'Enable','off') set(handles.submit_button,'Enable','off') set(handles.save_button,'Enable','off') set(handles.start_button,'Enable','off') set(handles.rows_size,'Enable','off') set(handles.columns_size,'Enable','off') set(handles.x_start,'Enable','off') set(handles.y_start,'Enable','off') set(handles.x_goal,'Enable','off') set(handles.y_goal,'Enable','off') set(handles.num_ob,'Enable','off') set(handles.CIA_button,'Enable','off') set(handles.A_button,'Enable','off') set(handles.weigted_button,'Enable','off') %set(handles.weight,'Enable','off') % --- Executes on button press in abort_button. function abort_button_Callback(hObject, eventdata, handles) % hObject handle to abort_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.stop_now = 1; guidata(hObject, handles); % Update handles structure function columns_size_Callback(hObject, eventdata, handles) % hObject handle to columns_size (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 columns_size as text % str2double(get(hObject,'String')) returns contents of columns_size as a double ValidEnviromentalParameters(hObject, eventdata, handles); guidata(hObject, handles); % Update handles structure % --- Executes during object creation, after setting all properties. function columns_size_CreateFcn(hObject, eventdata, handles) % hObject handle to columns_size (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 x_start_Callback(hObject, eventdata, handles) % hObject handle to x_start (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 x_start as text % str2double(get(hObject,'String')) returns contents of x_start as a double ValidEnviromentalParameters(hObject, eventdata, handles); guidata(hObject, handles); % Update handles structure % --- Executes during object creation, after setting all properties. function x_start_CreateFcn(hObject, eventdata, handles) % hObject handle to x_start (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 y_start_Callback(hObject, eventdata, handles) % hObject handle to y_start (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 y_start as text % str2double(get(hObject,'String')) returns contents of y_start as a double ValidEnviromentalParameters(hObject, eventdata, handles); guidata(hObject, handles); % Update handles structure % --- Executes during object creation, after setting all properties. function y_start_CreateFcn(hObject, eventdata, handles) % hObject handle to y_start (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 x_goal_Callback(hObject, eventdata, handles) % hObject handle to x_goal (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 x_goal as text % str2double(get(hObject,'String')) returns contents of x_goal as a double ValidEnviromentalParameters(hObject, eventdata, handles); guidata(hObject, handles); % Update handles structure % --- Executes during object creation, after setting all properties. function x_goal_CreateFcn(hObject, eventdata, handles) % hObject handle to x_goal (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 y_goal_Callback(hObject, eventdata, handles) % hObject handle to y_goal (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 y_goal as text % str2double(get(hObject,'String')) returns contents of y_goal as a double ValidEnviromentalParameters(hObject, eventdata, handles); guidata(hObject, handles); % Update handles structure % --- Executes during object creation, after setting all properties. function y_goal_CreateFcn(hObject, eventdata, handles) % hObject handle to y_goal (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 y=ValidEnviromentalParameters(hObject, eventdata, handles) y=0; %handles.ValidExperimntSetUp = 0; set(handles.save_button,'Enable','off') maxNumOfCells = 100; minNumOfCells = 2; maxPerObs = 0.7; %%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%% l_xGoal = str2num(get(handles.x_goal,'String')); l_yGoal = str2num(get(handles.y_goal,'String')); l_xStart = str2num(get(handles.x_start,'String')); l_yStart = str2num(get(handles.y_start,'String')); l_rowsSize = str2num(get(handles.rows_size,'String')); l_colsSize = str2num(get(handles.columns_size,'String')); l_numOb = str2num(get(handles.num_ob,'String')); set(handles.x_goal,'ForegroundColor','black') set(handles.y_goal,'ForegroundColor','black') set(handles.x_start,'ForegroundColor','black') set(handles.y_start,'ForegroundColor','black') set(handles.rows_size,'ForegroundColor','black') set(handles.columns_size,'ForegroundColor','black') set(handles.num_ob,'ForegroundColor','black') if isempty(l_rowsSize) || l_rowsSize>maxNumOfCells || l_rowsSize<minNumOfCells set(handles.rows_size,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif isempty(l_colsSize) || l_colsSize>maxNumOfCells || l_colsSize<minNumOfCells set(handles.columns_size,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif isempty(l_xGoal) || l_xGoal<1 set(handles.x_goal,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif isempty(l_yGoal) || l_yGoal<1 set(handles.y_goal,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif isempty(l_xStart) || l_xStart<1 set(handles.x_start,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif isempty(l_yStart) || l_yStart<1 set(handles.y_start,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif l_xGoal>l_rowsSize set(handles.rows_size,'ForegroundColor','red') set(handles.x_goal,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif l_yGoal>l_colsSize set(handles.columns_size,'ForegroundColor','red') set(handles.y_goal,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif l_xStart>l_rowsSize set(handles.rows_size,'ForegroundColor','red') set(handles.x_start,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif l_yStart>l_colsSize set(handles.columns_size,'ForegroundColor','red') set(handles.y_start,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') elseif isempty(l_numOb) || l_numOb>(l_rowsSize*l_colsSize)*maxPerObs || l_numOb<0 set(handles.num_ob,'ForegroundColor','red') set(handles.submit_button,'Enable','off') set(handles.start_button,'Enable','off') else set(handles.submit_button,'Enable','on') %set(handles.start_button,'Enable','on') y=1; end guidata(hObject, handles); % Update handles structure function methodgroup_CreateFcn(hObject, eventdata, handles) guidata(hObject, handles); % --- Executes when selected object is changed in methodgroup. function methodgroup_SelectionChangedFcn(hObject, eventdata, handles) % hObject handle to the selected object in methodgroup % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if strcmp(get(get(handles.methodgroup,'SelectedObject'),'Tag'),'weigted_button') set(handles.weight,'Enable','on') else set(handles.weight,'Enable','off') set(handles.weight,'String',handles.weightDefaultValue) weight_Callback(hObject, eventdata, handles) end guidata(hObject, handles); % Update handles structure % --- Executes during object deletion, before destroying properties. function CIA_button_DeleteFcn(hObject, eventdata, handles) % hObject handle to CIA_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
github
athakapo/Continuously-Informed-Heuristic-A---Optimal-path-retrieval-inside-an-unknown-environment-master
v2struct.m
.m
Continuously-Informed-Heuristic-A---Optimal-path-retrieval-inside-an-unknown-environment-master/matlabFunctions/v2struct.m
15,949
utf_8
20912a1f0ff4635fa430ce427d925be3
%% v2struct % v2struct Pack/Unpack Variables to/from a scalar structure. function varargout = v2struct(varargin) %% Description % v2struct has dual functionality in packing & unpacking variables into structures and % vice versa, according to the syntax and inputs. % % Function features: % * Pack variables to structure with enhanced field naming % * Pack and update variables in existing structure % * Unpack variables from structure with enhanced variable naming % * Unpack only specific fields in a structure to variables % * Unpack without over writing existing variables in work space % % In addition to the obvious usage, this function could by highly useful for example in % working with a function with multiple inputs. Packing variables before the call to % the function, and unpacking it in the beginning of the function will make the function % call shorter, more readable, and you would not have to worry about arguments order any % more. Moreover you could leave the function as it is and you could pass same inputs to % multiple functions, each of which will use its designated arguments placed in the % structure. % %% Syntax % Pack % S = v2struct % S = v2struct(x,y,z,...) % S = v2struct(fieldNames) % S = v2struct(A,B,C,..., fieldNames) % S = v2struct(x,..., nameOfStruct2Update, fieldNames) % v2struct % v2struct(x,y,z,...) % v2struct(fieldNames) % v2struct(A,B,C,..., fieldNames) % v2struct(x,..., nameOfStruct2Update, fieldNames) % % Unpack % v2struct(S) % [a,b,c,...] = v2struct(S) % v2struct(S,fieldNames) % [a,b,c,...] = v2struct(S,fieldNames) % %% Inputs & Outputs % Pack - inputs % x,y,z,... - any variable to pack. can be replaced by fieldNames below. % nameOfStruct2Update - optional, name of structure to update if desired. % fieldNames - optional, cell array of strings, which must include a cell % with the string 'fieldNames' and must be the last input. % Pack - outputs % S - the packed structure. If there is no output argument then a structure named % Sv2struct would be created in the caller workspace. % % Unpack - inputs % S - name of structure to be unpacked. % fieldNames - optional, cell array of strings, which must include a cell with the % string 'fieldNames' and must be the last input. % Unpack - outputs % a,b,c,... - variables upacked from the structure. % if there are no output arguments then variables would be created in % the caller workspace with naming according to name of inputs. % %% Examples % % see 'Usage example' section below for convenient presentation of these examples. % % % NOTE: whenever using filedNames cell array please note the following % % 1. fieldNames cell array must include a cell with the string 'fieldNames' % % 2. fieldNames cell array input must be the last input. % % % Pack % x = zeros(3); x2 = ones(3); y = 'Testing123'; z = cell(2,3); % fieldNames1 = {'fieldNames', 'x', 'y', 'z'}; % fieldNames2 = {'fieldNames', 'a', 'b', 'c'}; % fieldNames3 = {'fieldNames', 'x'}; % nameOfStruct2Update = 'S'; % % % The four examples below return structure S with same values however the % % structure's field names are defined differently in every syntax. % % Example 1. % % structure field names defined by variables names. % S = v2struct(x,y,z) % % Example 2. % % structure field names defined according to the cell array fieldNames. % % NOTE: variables with the names in fieldNames1 must exist in the caller workspace. % S = v2struct(fieldNames1) % % Example 3. % % same as #1. but arguments are passed explicitly % S = v2struct(zeros(3), 'Testing123', cell(2,3), fieldNames1) % % Example 4. % % field names defined by content of fieldNames2 while % % the values are set according to the passed arguments. In this case the structure % % S returned would be: S.a=x, S.b=y, S.c=z % S = v2struct(x,y,z, fieldNames2) % % % Example 5. % % update structure S. The fields that would be updated are according to content % % of fieldNames3. Note that you must pass a variable with the name % % 'nameOfStruct2Update' placed before 'fieldNames3'. This variable should contain % % the name of the structure you want to update as a string. Also note that if you % % set an output structure name which is different than the one stated in % % nameOfStruct2Update a new structure would be created and the structure that was % % meant to be updated would not get updated. % S.oldField = 'field to be saved for future use' % S = v2struct(x2, nameOfStruct2Update, fieldNames3) % % % Example 6. % % pack all variables in caller workspace. Call without input arguments. % S = v2struct % % % The following examples return the same results as the examples above but the % % structure would be returned with the default name 'Sv2struct'. Be cautious as % % this might lead to overriding of arguments. % % Example 7. % v2struct(x,y,z) % % Example 8. % v2struct(fieldNames1) % % Example 9. % v2struct(zeros(3), 'Testing123', cell(2,3), fieldNames1) % % Example 10. % v2struct(x,y,z, fieldNames2) % % Example 11. % S.oldField = 'field to be saved for future use' % v2struct(x2, nameOfStruct2Update, fieldNames3) % % Example 12. % v2struct % % % Unpack % clear S x x2 y z fieldNames1 fieldNames2 fieldNames3 nameOfStruct2Update % S.x = zeros(3); S.y = 'Testing123'; S.z = cell(2,3); % fieldNames3 = {'fieldNames','x','z'}; % % % Example 1. % % This example creates or overwrites variables x, y, z in the caller with the % % contents of the corresponding named fields. % v2struct(S) % % % Example 2. % % This example assigns the contents of the fields of the scalar structure % % S to the variables a,b,c rather than overwriting variables in the caller. If % % there are fewer output variables than there are fields in S, the remaining fields % % are not extracted. % [a,b,c] = v2struct(S) % % % Example 3. % % This example creates or overwrites variables x and z in the caller with the % % contents of the corresponding named fields. % v2struct(S, fieldNames3) % % % Example 4. % % This example assigns the contents of the fields 'x' and 'z' defined by % % fieldNames3 of the scalar structure S to the variables a and b rather than % % overwriting variables in the caller. If there are fewer output variables than % % there are fields in S, the remaining fields are not extracted. % [a,b] = v2struct(S, fieldNames3) % % % This example unpacks variables 'y' and 'z' only without overwriting variable 'x'. % % NOTE the addition of the field named 'avoidOverWrite' to the structure to be % % unpacked. This is mandatory in order to make this functionality work. The % % contents of this field can be anything, it does not matter. % S.avoidOverWrite = ''; % x = 'do not overwrite me'; % v2struct(S) % %% Usage example (includes sub-functions) % 1. run attached v2structDemo1.m file for on screen presentation of examples. % 2. run attached v2structDemo2.m file and read comments in file for a suggestion of % how to use v2struct in managing input to other functions with improved usability. % %% Revision history % 2011-05-19, Adi N., Creation % 2011-05-29, Adi N., Update structure added, some documentation and demo function changes % 2011-06-02, Adi N., Fixed updating structure functionality % 2011-06-05, Adi N., Added functionality: avoid overwritring existing variables, added % unpacking examples to demo1 .m file. % 2011-06-30, Adi N., fieldNames usage corrected, now must include a specific string to % be triggered. Documentation enhanced. Code tweaked. % 2011-07-14, Adi N., Fixed bug in packing with variables only % 2011-08-14, Adi N., Clarified warning and error when packing/unpacking with % fieldNames. % 2011-09-12, Adi N., Added easy packing of all variables in caller workspace (thanks % to Vesa Lehtinen for the suggestion), fixed bug in warning % handling in packing case, edited comments. % % Inspired by the function: mmv2truct - D.C. Hanselman, University of Maine, Orono, ME % 04469 4/28/99, 9/29/99, renamed 10/19/99 Mastering MATLAB 5, Prentice Hall, % ISBN 0-13-858366-8 % parse input for field names if isempty(varargin) gotCellArrayOfStrings = false; toUnpackRegular = false; toUnpackFieldNames = false; gotFieldNames = false; else gotCellArrayOfStrings = iscellstr(varargin{end}); toUnpackRegular = (nargin == 1) && isstruct(varargin{1}); if toUnpackRegular fieldNames = fieldnames(varargin{1})'; nFields = length(fieldNames); end gotFieldNames = gotCellArrayOfStrings & any(strcmpi(varargin{end},'fieldNames')); if gotFieldNames fieldNamesRaw = varargin{end}; % indices of cells with actual field names, leaving out the index to 'fieldNames' cell. indFieldNames = ~strcmpi(fieldNamesRaw,'fieldNames'); fieldNames = fieldNamesRaw(indFieldNames); nFields = length(fieldNames); end toUnpackFieldNames = (nargin == 2) && isstruct(varargin{1}) && gotFieldNames; end % Unpack if toUnpackRegular || toUnpackFieldNames struct = varargin{1}; assert(isequal(length(struct),1) , 'Single input nust be a scalar structure.'); CallerWS = evalin('caller','whos'); % arguments in caller work space % update fieldNames according to 'avoidOverWrite' flag field. if isfield(struct,'avoidOverWrite') indFieldNames = ~ismember(fieldNames,{CallerWS(:).name,'avoidOverWrite'}); fieldNames = fieldNames(indFieldNames); nFields = length(fieldNames); end if toUnpackRegular % Unpack with regular fields order if nargout == 0 % assign in caller for iField = 1:nFields assignin('caller',fieldNames{iField},struct.(fieldNames{iField})); end else % dump into variables for iField = 1:nargout varargout{iField} = struct.(fieldNames{iField}); end end elseif toUnpackFieldNames % Unpack with fields according to fieldNames if nargout == 0 % assign in caller, by comparing fields to fieldNames for iField = 1:nFields assignin('caller',fieldNames{iField},struct.(fieldNames{iField})); end else % dump into variables assert( isequal(nFields, nargout) , ['Number of output arguments',... ' does not match number of field names in cell array']); for iField = 1:nFields varargout{iField} = struct.(fieldNames{iField}); end end end % Pack else % build cell array of input names CallerWS = evalin('caller','whos'); inputNames = cell(1,nargin); for iArgin = 1:nargin inputNames{iArgin} = inputname(iArgin); end nInputs = length(inputNames); % look for 'nameOfStruct2Update' variable and get the structure name if ~any(strcmpi(inputNames,'nameOfStruct2Update')) % no nameOfStruct2Update nameStructArgFound = false; validVarargin = varargin; else % nameOfStruct2Update found nameStructArgFound = true; nameStructArgLoc = strcmp(inputNames,'nameOfStruct2Update'); nameOfStruct2Update = varargin{nameStructArgLoc}; % valid varargin with just the inputs to pack and fieldNames if exists validVarargin = varargin(~strcmpi(inputNames,'nameOfStruct2Update')); % valid inputNames with just the inputs name to pack and fieldNames if exists inputNames = inputNames(~strcmpi(inputNames,'nameOfStruct2Update')); nInputs = length(inputNames); % copy structure from caller workspace to enable its updating if ismember(nameOfStruct2Update,{CallerWS(:).name}) % verify existance S = evalin('caller',nameOfStruct2Update); else error(['Bad input. Structure named ''',nameOfStruct2Update,... ''' was not found in workspace']) end end % when there is no input or the input is only variables and perhaps % also nameOfStruct2Update if ~gotFieldNames % no input, pack all of variables in caller workspace if isequal(nInputs, 0) for iVar = 1:length(CallerWS) S.(CallerWS(iVar).name) = evalin('caller',CallerWS(iVar).name); end % got input, check input names and pack else for iInput = 1:nInputs if gotCellArrayOfStrings % called with a cell array of strings errMsg = sprintf(['Bad input in cell array of strings.'... '\nIf you want to pack (or unpack) using this cell array as'... ' designated names'... '\nof the structure''s fields, add a cell with the string'... ' ''fieldNames'' to it.']); else errMsg = sprintf(['Bad input in argument no. ', int2str(iArgin),... ' - explicit argument.\n'... 'Explicit arguments can only be called along with a matching'... '\n''fieldNames'' cell array of strings.']); end assert( ~isempty(inputNames{iInput}), errMsg); S.(inputNames{iInput}) = validVarargin{iInput}; end % issue warning for possible wrong usage when packing with an input of cell array of % strings as the last input without it containing the string 'fieldNames'. if gotCellArrayOfStrings name = inputNames{end}; % input contains structure and a cell array of strings if (nargin == 2) && isstruct(varargin{1}) msgStr = [inputNames{1},''' and ''',inputNames{2},''' were']; % input contains any arguments with an implicit cell array of strings else msgStr = [name, ''' was']; end warnMsg = ['V2STRUCT - ''%s packed in the structure.'... '\nTo avoid this warning do not put ''%s'' as last v2struct input.'... '\nIf you want to pack (or unpack) using ''%s'' as designated names'... ' of the'... '\nstructure''s fields, add a cell with the string ''fieldNames'' to'... ' ''%s''.']; fprintf('\n') warning('MATLAB:V2STRUCT:cellArrayOfStringNotFieldNames',warnMsg,msgStr,... name,name,name) end end % fieldNames cell array exists in input elseif gotFieldNames nVarToPack = length(varargin)-1-double(nameStructArgFound); if nVarToPack == 0 % no variables to pack for iField = 1:nFields S.(fieldNames{iField}) = evalin('caller',fieldNames{iField}); end % else - variables to pack exist % check for correct number of fields vs. variables to pack elseif ~isequal(nFields,nVarToPack) error(['Bad input. Number of strings in fieldNames does not match',... 'number of input arguments for packing.']) else for iField = 1:nFields S.(fieldNames{iField}) = validVarargin{iField}; end end end % if ~gotFieldNames if nargout == 0 assignin( 'caller', 'Sv2struct',S ); else varargout{1} = S; end end % if nargin
github
robical/BlindSourceSeparation-master
wavexread.m
.m
BlindSourceSeparation-master/wavexread.m
20,102
utf_8
f35f68e29ec4b1545c1597f333b27469
function [y,Fs,nbits,speakers] = wavexread(file,ext) %WAVEXREAD Read Microsoft WAVE-FORMAT-EXTENSIBLE (".wav") sound file. % Y=WAVEXREAD(FILE) reads a WAVE file specified by the string FILE, % returning the sampled data in Y. The ".wav" extension is appended % if no extension is given. Amplitude values are in the range [-1,+1]. % % [Y,FS,NBITS]=WAVEXREAD(FILE) returns the sample rate (FS) in Hertz % and the number of bits per sample (NBITS) used to encode the % data in the file. % % [...]=WAVEXREAD(FILE,N) returns only the first N samples from each % channel in the file. % [...]=WAVEXREAD(FILE,[N1 N2]) returns only samples N1 through N2 from % each channel in the file. % SIZ=WAVEXREAD(FILE,'size') returns the size of the audio data contained % in the file in place of the actual audio data, returning the % vector SIZ=[samples channels]. % % [Y,FS,NBITS,OPTS]=WAVEXREAD(...) returns a structure OPTS of additional % information contained in the WAV file. The content of this % structure differs from file to file. Typical structure fields % include '.fmt' (audio format information) and '.info' (text % which may describe subject title, copy right, etc.) % % Supports multi-channel data, with up to 32 bits per sample. % % NOTE: This file reader only supports Microsoft PCM data format. % It does not support wave-list data. % % See also WAVEXWRITE, WAVWRITE, AUREAD, AUWRITE. % Author: D. Orofino % Copyright 1984-2002 The MathWorks, Inc. % $Revision: 5.28 $ $Date: 2002/05/30 20:42:03 $ % % Modified 2004/07/27 by Sylvain Choisel % to handle WAVE-FORMAT-EXTENSIBLE % Parse input arguments: nargchk(1,2,nargin); if nargin<2, ext=[]; end % Default - read all samples exts = prod(size(ext)); % length of extent info if ~strncmpi(ext,'size',exts) & (exts > 2), error('Index range must be specified as a scalar or 2-element vector.'); end if ~ischar(ext) & exts==1, if ext==0, ext='size'; % synonym for size else ext=[1 ext]; % Prepend start sample index end end % Open WAV file: [fid,msg] = open_wav(file); error(msg); % Now the file is open - wrap remaining code in try/catch so we can % close the file if an error occurs try % Find the first RIFF chunk: [riffck,msg] = find_cktype(fid,'RIFF'); %error(msg); if ~isempty(msg), error('Not a WAVE file.'); end % Verify that RIFF file is WAVE data type: msg = check_rifftype(fid,'WAVE'); error(msg); % Find optional chunks, and don't stop till <data-ck> found: found_data = 0; end_of_file = 0; opt_ck = []; while(~end_of_file), [ck,msg] = find_cktype(fid); error(msg); switch lower(ck.ID) case 'end of file' end_of_file = 1; case 'fmt' % <fmt-ck> found [opt_ck,msg] = read_wavefmt(fid,ck,opt_ck); error(msg); case 'data' % <data-ck> found: found_data = 1; if ~isfield(opt_ck,'fmt'), error('Corrupt WAV file: found audio data before format information.'); end if strncmpi(ext,'size',exts) | ... (~isempty(ext) & all(ext==0)), % Caller doesn't want data - just data size: [samples,msg] = read_wavedat(ck, opt_ck.fmt, -1); error(msg); y = [samples opt_ck.fmt.nChannels]; else % Read <wave-data>: [datack,msg] = read_wavedat(ck, opt_ck.fmt, ext); error(msg); y = datack.Data; end case 'fact' % Optional <fact-ck> found: [opt_ck,msg] = read_factck(fid, ck, opt_ck); error(msg); case 'disp' % Optional <disp-ck> found: [opt_ck,msg] = read_dispck(fid, ck, opt_ck); error(msg); case 'list' % Optional <list-ck> found: [opt_ck, msg] = read_listck(fid, ck, opt_ck); error(msg); otherwise % Skip over data in unprocessed chunks: if rem(ck.Size,2), ck.Size=ck.Size+1; end if(fseek(fid,ck.Size,0)==-1), error('Incorrect chunk size information in WAV file.'); end end end catch fclose(fid); error(lasterr); end fclose(fid); % Parse structure info for return to user: Fs = opt_ck.fmt.nSamplesPerSec; if opt_ck.fmt.wFormatTag == 1 | opt_ck.fmt.wFormatTag == 3, % Type 3 floating point has no nBitsPerSample field, so use % nBlockAlign to figure out number of bits nbits = (opt_ck.fmt.nBlockAlign / opt_ck.fmt.nChannels) * 8; else nbits = []; % Unknown end speakers=find((fliplr(dec2bin(opt_ck.fmt.dwChanelMask)-48))~=0); % end of wavread() % ------------------------------------------------------------------------ % Local functions: % ------------------------------------------------------------------------ % --------------------------------------------- % OPEN_WAV: Open a WAV file for reading % --------------------------------------------- function [fid,msg] = open_wav(file) % Append .wav extension if it's missing: [pat,nam,ext] = fileparts(file); if isempty(ext), file = [file '.wav']; end [fid,msg] = fopen(file,'rb','l'); % Little-endian if fid == -1, msg = 'Cannot open file.'; end return % --------------------------------------------- % READ_CKINFO: Reads next RIFF chunk, but not the chunk data. % If optional sflg is set to nonzero, reads SUBchunk info instead. % Expects an open FID pointing to first byte of chunk header. % Returns a new chunk structure. % --------------------------------------------- function [ck,msg] = read_ckinfo(fid) msg = ''; ck.fid = fid; ck.Data = []; err_msg = 'Truncated chunk header found - possibly not a WAV file.'; [s,cnt] = fread(fid,4,'char'); % Do not error-out if a few (<4) trailing chars are in file % Just return quickly: if (cnt~=4), if feof(fid), % End of the file (not an error) ck.ID = 'end of file'; % unambiguous chunk ID (>4 chars) ck.Size = 0; else msg = err_msg; end return end ck.ID = deblank(setstr(s')); % Read chunk size (skip if subchunk): [sz,cnt] = fread(fid,1,'ulong'); if cnt~=1, msg = err_msg; return end ck.Size = sz; return % --------------------------------------------- % FIND_CKTYPE: Finds a chunk with appropriate type. % Searches from current file position specified by fid. % Leaves file positions to data of desired chunk. % If optional sflg is set to nonzero, finds a SUBchunk instead. % --------------------------------------------- function [ck,msg] = find_cktype(fid,ftype) msg = ''; if nargin<2, ftype = ''; end [ck,msg] = read_ckinfo(fid); if ~isempty(msg), return; end % Was a required chunk type specified? if ~isempty(ftype) & ~strcmpi(ck.ID,ftype), msg = ['<' ftype '-ck> did not appear as expected']; end return % --------------------------------------------- % CHECK_RIFFTYPE: Finds the RIFF data type. % Searches from current file position specified by fid. % Leaves file positions to data of desired chunk. % --------------------------------------------- function msg = check_rifftype(fid,ftype) msg = ''; [rifftype,cnt] = fread(fid,4,'char'); rifftype = setstr(rifftype)'; if cnt~=4, msg = 'Not a WAVE file.'; elseif ~strcmpi(rifftype,ftype), msg = ['File does not contain required ''' ftype ''' data chunk.']; end return % --------------------------------------------- % READ_LISTCK: Read the FLIST chunk: % --------------------------------------------- function [opt_ck,msg] = read_listck(fid,ck, orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 4; % # of required bytes in <list-ck> header msg = ''; err_msg = 'Error reading <list-ck> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <list-ck> data: listdata = setstr(fread(fid,total_bytes,'uchar')'); listtype = lower(listdata(1:4)); % Get LIST type listdata = listdata(5:end); % Move past INFO if strcmp(listtype,'info'), % Information: while(~isempty(listdata)), id = listdata(1:4); switch lower(id) case 'iart' name = 'Artist'; case 'icmt' name = 'Comments'; case 'icrd' name = 'Creation date'; case 'icop' name = ['Copy' 'right']; case 'ieng' name = 'Engineer'; case 'inam' name = 'Name'; case 'iprd' name = 'Product'; case 'isbj' name = 'Subject'; case 'isft' name = 'Software'; case 'isrc' name = 'Source'; otherwise name = id; end if ~isfield(opt_ck,'info'), opt_ck.info = []; end len = listdata(5:8) * 2.^[0 8 16 24]'; txt = listdata(9:9+len-1); % Fix up text: deblank, and replace CR/LR with LF txt = deblank(txt); idx=findstr(txt,setstr([13 10])); txt(idx) = ''; % Store - don't include the "name" info opt_ck.info.(lower(id)) = txt; if rem(len,2), len=len+1; end listdata = listdata(9+len:end); end else if ~isfield(opt_ck,'list'), opt_ck.list = []; end opt_ck.list.(listtype) = listdata; end % Skip over any unprocessed data: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - (ftell(fid) - orig_pos); if rbytes~=0, if (fseek(fid,rbytes,'cof')==-1), msg = err_msg; end end return % --------------------------------------------- % READ_DISPCK: Read the DISP chunk: % --------------------------------------------- function [opt_ck, msg] = read_dispck(fid,ck,orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 4; % # of required bytes in <disp-ck> header msg = ''; err_msg = 'Error reading <disp-ck> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <disp-ck> data: data = fread(fid,total_bytes,'uchar'); % Process data: % First few entries are size info: icon_data = data; siz_info = reshape(icon_data(1:2*4),4,2)'; siz_info = siz_info*(2.^[0 8 16 24]'); is_icon = isequal(siz_info,[8;40]); if ~is_icon, % Not the icon: opt_ck.disp.name = 'DisplayName'; txt = deblank(setstr(data(5:end)')); opt_ck.disp.text = txt; end % Skip over any unprocessed data: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - (ftell(fid) - orig_pos); if rbytes~=0, if(fseek(fid,rbytes,'cof')==-1), msg = err_msg; end end return % --------------------------------------------- % READ_FACTCK: Read the FACT chunk: % --------------------------------------------- function [opt_ck,msg] = read_factck(fid,ck,orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 4; % # of required bytes in <fact-ck> header msg = ''; err_msg = 'Error reading <fact-ck> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <fact-ck> data: opt_ck.fact = setstr(fread(fid,total_bytes,'uchar')'); % Skip over any unprocessed data: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - (ftell(fid) - orig_pos); if rbytes~=0, if(fseek(fid,rbytes,'cof')==-1), msg = err_msg; end end return % --------------------------------------------- % READ_WAVEFMT: Read WAVE format chunk. % Assumes fid points to the <wave-fmt> subchunk. % Requires chunk structure to be passed, indicating % the length of the chunk in case we don't recognize % the format tag. % --------------------------------------------- function [opt_ck,msg] = read_wavefmt(fid,ck,orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 40; % # of required bytes in <wave-format> header msg = ''; err_msg = 'Error reading <wave-fmt> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <wave-format> data: opt_ck.fmt.wFormatTag = fread(fid,1,'ushort'); % Data encoding format opt_ck.fmt.nChannels = fread(fid,1,'ushort'); % Number of channels opt_ck.fmt.nSamplesPerSec = fread(fid,1,'ulong'); % Samples per second opt_ck.fmt.nAvgBytesPerSec = fread(fid,1,'ulong'); % Avg transfer rate opt_ck.fmt.nBlockAlign = fread(fid,1,'ushort'); % Block alignment %sc opt_ck.fmt.wBitsPerSample = fread(fid,1,'ushort'); opt_ck.fmt.cbSize = fread(fid,1,'ushort'); opt_ck.fmt.wValidBitsPerSample = fread(fid,1,'ushort'); opt_ck.fmt.dwChanelMask = fread(fid,1,'ulong'); opt_ck.fmt.subFormat = fread(fid,16,'uchar'); % Read format-specific info: switch opt_ck.fmt.wFormatTag case 1 % PCM Format: %[opt_ck.fmt, msg] = read_fmt_pcm(fid, ck, opt_ck.fmt); exit('Invalid extensible format'); case hex2dec('FFFE') % [opt_ck.fmt, msg] = read_fmt_pcm(fid, ck, opt_ck.fmt); end % Skip over any unprocessed fmt-specific data: %if rem(total_bytes,2), total_bytes=total_bytes+1; end %rbytes = total_bytes - (ftell(fid) - orig_pos); %if rbytes~=0, % if(fseek(fid,rbytes,'cof')==-1), % msg = err_msg; % end %end return % --------------------------------------------- % READ_FMT_PCM: Read <PCM-format-specific> info % --------------------------------------------- function [fmt,msg] = read_fmt_pcm(fid, ck, fmt) % There had better be a bits/sample field: total_bytes = ck.Size; % # bytes in subchunk nbytes = 14; % # of bytes already read in <wave-format> header msg = ''; err_msg = 'Error reading PCM <wave-fmt> chunk.'; %if (total_bytes < nbytes+2), % msg = err_msg; % return %end %[bits,cnt] = fread(fid,1,'ushort'); %nbytes=nbytes+2; %if (cnt~=1), % msg = err_msg; % return %end %fmt.nBitsPerSample=bits; % Are there any additional fields present? if (total_bytes > nbytes), % See if the "cbSize" field is present. If so, grab the data: if (total_bytes >= nbytes+2), % we have the cbSize ushort in the file: [cbSize,cnt]=fread(fid,1,'ushort'); nbytes=nbytes+2; if (cnt~=1), msg = err_msg; return end fmt.cbSize = cbSize; end % Simply skip any remaining stuff - we don't know what it is: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - nbytes; if rbytes~=0, if (fseek(fid,rbytes,'cof') == -1); msg = err_msg; end end end return % --------------------------------------------- % READ_WAVEDAT: Read WAVE data chunk % Assumes fid points to the wave-data chunk % Requires <data-ck> and <wave-format> structures to be passed. % Requires extraction range to be specified. % Setting ext=[] forces ALL samples to be read. Otherwise, % ext should be a 2-element vector specifying the first % and last samples (per channel) to be extracted. % Setting ext=-1 returns the number of samples per channel, % skipping over the sample data. % --------------------------------------------- function [dat,msg] = read_wavedat(datack,wavefmt,ext) % In case of unsupported data compression format: dat = []; fmt_msg = ''; switch wavefmt.wFormatTag case 1 % PCM Format: [dat,msg] = read_dat_pcm(datack,wavefmt,ext); case 2 fmt_msg = 'Microsoft ADPCM'; case 3 % normalized floating-point [dat,msg] = read_dat_pcm(datack,wavefmt,ext); case 6 fmt_msg = 'CCITT a-law'; case 7 fmt_msg = 'CCITT mu-law'; case 17 fmt_msg = 'IMA ADPCM'; case 34 fmt_msg = 'DSP Group TrueSpeech TM'; case 49 fmt_msg = 'GSM 6.10'; case 50 fmt_msg = 'MSN Audio'; case 257 fmt_msg = 'IBM Mu-law'; case 258 fmt_msg = 'IBM A-law'; case 259 fmt_msg = 'IBM AVC Adaptive Differential'; case hex2dec('FFFE') %sc % WAVE-FORMAT-EXTENSIBLE [dat,msg] = read_dat_pcm(datack,wavefmt,ext); otherwise fmt_msg = ['Format #' num2str(wavefmt.wFormatTag)]; end if ~isempty(fmt_msg), msg = ['Data compression format (' fmt_msg ') is not supported.']; end return % --------------------------------------------- % READ_DAT_PCM: Read PCM format data from <wave-data> chunk. % Assumes fid points to the wave-data chunk % Requires <data-ck> and <wave-format> structures to be passed. % Requires extraction range to be specified. % Setting ext=[] forces ALL samples to be read. Otherwise, % ext should be a 2-element vector specifying the first % and last samples (per channel) to be extracted. % Setting ext=-1 returns the number of samples per channel, % skipping over the sample data. % --------------------------------------------- function [dat,msg] = read_dat_pcm(datack,wavefmt,ext) dat = []; msg = ''; % Determine # bytes/sample - format requires rounding % to next integer number of bytes: BytesPerSample = ceil(wavefmt.nBlockAlign / wavefmt.nChannels); if (BytesPerSample == 1), dtype='uchar'; % unsigned 8-bit elseif (BytesPerSample == 2), dtype='short'; % signed 16-bit elseif (BytesPerSample == 3) dtype='bit24'; % signed 24-bit elseif (BytesPerSample == 4), % 32-bit 16.8 float (type 1 - 32-bit) % 32-bit normalized floating point dtype = 'float'; % 32-bit 24.0 float (type 1 - 24-bit) if wavefmt.wFormatTag ~= 3 & wavefmt.nBitsPerSample == 24, BytesPerSample = 3; end else msg = 'Cannot read PCM file formats with more than 32 bits per sample.'; return end total_bytes = datack.Size; % # bytes in this chunk total_samples = total_bytes / BytesPerSample; SamplesPerChannel = total_samples / wavefmt.nChannels; if ~isempty(ext) & ext==-1, % Just return the samples per channel, and fseek past data: dat = SamplesPerChannel; % Add in a pad-byte, if required: total_bytes = total_bytes + rem(datack.Size,2); if(fseek(datack.fid,total_bytes,'cof')==-1), msg = 'Error reading PCM file format.'; end return end % Determine sample range to read: if isempty(ext), ext = [1 SamplesPerChannel]; % Return all samples else if prod(size(ext))~=2, msg = 'Sample limit vector must have 2 elements.'; return end if ext(1)<1 | ext(2)>SamplesPerChannel, msg = 'Sample limits out of range.'; return end if ext(1)>ext(2), msg = 'Sample limits must be given in ascending order.'; return end end bytes_remaining = total_bytes; % Preset byte counter % Skip over leading samples: if ext(1)>1, % Skip over leading samples, if specified: skipcnt = BytesPerSample * (ext(1)-1) * wavefmt.nChannels; if(fseek(datack.fid, skipcnt,'cof') == -1), msg = 'Error reading PCM file format.'; return end % % Update count of bytes remaining: bytes_remaining = bytes_remaining - skipcnt; end % Read desired data: nSPCext = ext(2)-ext(1)+1; % # samples per channel in extraction range dat = datack; % Copy input structure to output extSamples = wavefmt.nChannels*nSPCext; dat.Data = fread(datack.fid, [wavefmt.nChannels nSPCext], dtype); % % Update count of bytes remaining: skipcnt = BytesPerSample*nSPCext*wavefmt.nChannels; bytes_remaining = bytes_remaining - skipcnt; % if cnt~=extSamples, dat='Error reading file.'; return; end % Skip over trailing samples: if(fseek(datack.fid, BytesPerSample * ... (SamplesPerChannel-ext(2))*wavefmt.nChannels, 'cof')==-1), msg = 'Error reading PCM file format.'; return end % Update count of bytes remaining: skipcnt = BytesPerSample*(SamplesPerChannel-ext(2))*wavefmt.nChannels; bytes_remaining = bytes_remaining - skipcnt; % Determine if a pad-byte is appended to data chunk, % skipping over it if present: if rem(datack.Size,2), fseek(datack.fid, 1, 'cof'); end % Rearrange data into a matrix with one channel per column: dat.Data = dat.Data'; % Normalize data range: min will hit -1, max will not quite hit +1. if BytesPerSample==1, dat.Data = (dat.Data-128)/128; % [-1,1) elseif BytesPerSample==2, dat.Data = dat.Data/32768; % [-1,1) elseif BytesPerSample==3, dat.Data = dat.Data/(2^23); % [-1,1) elseif BytesPerSample==4, if wavefmt.wFormatTag ~= 3, % Type 3 32-bit is already normalized dat.Data = dat.Data/32768; % [-1,1) end end return % end of wavread.m
github
robical/BlindSourceSeparation-master
wavexwrite.m
.m
BlindSourceSeparation-master/wavexwrite.m
8,855
utf_8
5e65dd381efc54d3f9865c9c79100c35
function wavexwrite(y,Fs,nbits,wavefile,speakers) %WAVEXWRITE Write WAVE_FORMAT_EXTENSIBLE sound file. % WAVEXWRITE(Y,FS,NBITS,WAVEFILE, SPEAKERS) writes data Y to a WAVEX % file specified by the file name WAVEFILE, with a sample rate % of FS Hz and with NBITS number of bits. NBITS must be 8, 16, % 24, or 32. Stereo data should be specified as a matrix with two % columns. For NBITS < 32, amplitude values outside the range % [-1,+1] are clipped. % % SPEAKERS is a vector of speaker numbers % e.g. [1,2] for stereo % [1:5] for 5.1 % [3] for center channel % % WAVEXWRITE(Y,FS,WAVEFILE) assumes NBITS=16 bits. % WAVEXWRITE(Y,WAVEFILE) assumes NBITS=16 bits and FS=44100 Hz. % % 8-, 16-, and 24-bit files are type 1 integer PCM. 32-bit files % are written as type 3 normalized floating point. % % Modified 2004/07/27 by Sylvain Choisel % to handle WAVE-FORMAT-EXTENSIBLE % email: [email protected] % Parse inputs: error(nargchk(2,5,nargin)); if nargin < 3, wavefile = Fs; Fs = 44100; nbits = 16; elseif nargin < 4, wavefile = nbits; nbits = 16; end % If input is a vector, force it to be a column: if ndims(y) > 2, error('Data array cannot be an N-D array.'); end if size(y,1)==1, y = y(:); end [samples, channels] = size(y); if nargin < 5, speakerMask=2^channels-1; else if (length(speakers)~=channels) error ('Speaker mask length must be equal to the number of channels'); end speakerMask=sum(2.^(speakers-1)); end % Determine number of bytes in chunks % (not including pad bytes, if needed): % ---------------------------------- % 'RIFF' 4 bytes % size 4 bytes (ulong) % 'WAVE' 4 bytes % 'fmt ' 4 bytes % size 4 bytes (ulong) % <wave-format> 14 bytes % <format_specific> 2 bytes (PCM) % 'data' 4 bytes % size 4 bytes (ulong) % <wave-data> N bytes % ---------------------------------- bytes_per_sample = ceil(nbits/8); total_samples = samples * channels; total_bytes = total_samples * bytes_per_sample; riff_cksize = 4+48+total_bytes; % Don't include 'RIFF' or its size field fmt_cksize = 40; % Don't include 'fmt ' or its size field data_cksize = total_bytes; % Don't include 'data' or its size field % Determine pad bytes: data_pad = rem(data_cksize,2); riff_cksize = riff_cksize + data_pad; % + fmt_pad, always 0 % Open file for output: [fid,err] = OpenWaveWrite(wavefile); error(err); % Prepare basic chunk structure fields: ck=[]; ck.fid=fid; ck.filename = wavefile; % Write RIFF chunk: ck.ID = 'RIFF'; ck.Size = riff_cksize; error(write_ckinfo(ck)); % Write WAVE subchunk: ck.ID = 'WAVE'; ck.Size = []; % Indicate a subchunk (no chunk size) error(write_ckinfo(ck)); % Write <fmt-ck>: ck.ID = 'fmt '; ck.Size = fmt_cksize; error(write_ckinfo(ck)); % Write <wave-format>: fmt.filename = wavefile; fmt.wFormatTag = hex2dec('FFFE'); fmt.nChannels = channels; % Number of channels fmt.nSamplesPerSec = Fs; % Samples per second fmt.nAvgBytesPerSec = channels*bytes_per_sample*Fs; % Avg transfer rate fmt.nBlockAlign = channels*bytes_per_sample; % Block alignment fmt.nBitsPerSample = 8*bytes_per_sample; fmt.cbSize = 22; fmt.wValidBitsPerSample = nbits; fmt.dwSpkMask = speakerMask; fmt.subFormat = [1 0 0 0 0 0 16 0 8*16 0 0 hex2dec('AA') 0 hex2dec('38') hex2dec('9B') hex2dec('71')]; error(write_wavefmt(fid,fmt)); % Write <data-ck>: ck.ID = 'data'; ck.Size = data_cksize; error(write_ckinfo(ck)); % Write <wave-data>, and its pad byte if needed: error(write_wavedat(fid,fmt,y)); % Close file: fclose(fid); % end of wavwrite() % ------------------------------------------------------------------------ % Private functions: % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ function [fid,err] = OpenWaveWrite(wavefile) % OpenWaveWrite % Open WAV file for writing. % If filename does not contain an extension, add ".wav" fid = []; err = ''; if ~isstr(wavefile), err='Wave file name must be a string.'; return; end % modified 27/07/2004 sc %if isempty(findstr(wavefile,'.')), % wavefile=[wavefile '.wav']; %end [pathstr,name,ext,versn]=fileparts(wavefile); if (~strcmp(lower(ext),'.wav')) wavefile=[wavefile '.wav']; end % Open file, little-endian: [fid,err] = fopen(wavefile,'wb','l'); return % ------------------------------------------------------------------------ function err = write_ckinfo(ck) % WRITE_CKINFO: Writes next RIFF chunk, but not the chunk data. % Assumes the following fields in ck: % .fid File ID to an open file % .ID 4-character string chunk identifier % .Size Size of chunk (empty if subchunk) % % % Expects an open FID pointing to first byte of chunk header, % and a chunk structure. % ck.fid, ck.ID, ck.Size, ck.Data errmsg = ['Failed to write ' ck.ID ' chunk to WAVE file: ' ck.filename]; err = ''; if (fwrite(ck.fid, ck.ID, 'char') ~= 4), err=errmsg; return; end if ~isempty(ck.Size), % Write chunk size: if (fwrite(ck.fid, ck.Size, 'ulong') ~= 1), err=errmsg; return; end end return % ------------------------------------------------------------------------ function err = write_wavefmt(fid, fmt) % WRITE_WAVEFMT: Write WAVE format chunk. % Assumes fid points to the wave-format subchunk. % Requires chunk structure to be passed, indicating % the length of the chunk. errmsg = ['Failed to write WAVE format chunk to file' fmt.filename]; err = ''; % Create <wave-format> data: if (fwrite(fid, fmt.wFormatTag, 'ushort') ~= 1) | ... (fwrite(fid, fmt.nChannels, 'ushort') ~= 1) | ... (fwrite(fid, fmt.nSamplesPerSec, 'ulong' ) ~= 1) | ... (fwrite(fid, fmt.nAvgBytesPerSec, 'ulong' ) ~= 1) | ... (fwrite(fid, fmt.nBlockAlign, 'ushort') ~= 1) | ... (fwrite(fid, fmt.nBitsPerSample, 'ushort') ~= 1) | ... (fwrite(fid, fmt.cbSize, 'ushort') ~= 1) | ... (fwrite(fid, fmt.wValidBitsPerSample, 'ushort') ~= 1) | ... (fwrite(fid, fmt.dwSpkMask, 'ulong' ) ~= 1) | ... (fwrite(fid, fmt.subFormat, 'uchar' ) ~= 16) err=errmsg; end return % ----------------------------------------------------------------------- function y = PCM_Quantize(x, fmt) % PCM_Quantize: % Scale and quantize input data, from [-1, +1] range to % either an 8-, 16-, or 24-bit data range. % Clip data to normalized range [-1,+1]: ClipMsg = ['Data clipped during write to file:' fmt.filename]; ClipWarn = 0; % Determine slope (m) and bias (b) for data scaling: nbits = fmt.nBitsPerSample; m = 2.^(nbits-1); switch nbits case 8, b=128; case {16,24}, b=0; otherwise, error('Invalid number of bits specified.'); end y = round(m .* x + b); % Determine quantized data limits, based on the % presumed input data limits of [-1, +1]: ylim = [-1 +1]; qlim = m * ylim + b; qlim(2) = qlim(2)-1; % Clip data to quantizer limits: i = find(y < qlim(1)); if ~isempty(i), warning(ClipMsg); ClipWarn=1; y(i) = qlim(1); end i = find(y > qlim(2)); if ~isempty(i), if ~ClipWarn, warning(ClipMsg); end y(i) = qlim(2); end return % ----------------------------------------------------------------------- function err = write_wavedat(fid,fmt,data) % WRITE_WAVEDAT: Write WAVE data chunk % Assumes fid points to the wave-data chunk % Requires <wave-format> structure to be passed. err = ''; if fmt.wFormatTag==1 | fmt.wFormatTag==3 | fmt.wFormatTag==hex2dec('FFFE'), % PCM Format % 32-bit Type 3 is normalized, so no scaling needed. if fmt.nBitsPerSample ~= 32, data = PCM_Quantize(data, fmt); end switch fmt.nBitsPerSample case 8, dtype='uchar'; % unsigned 8-bit case 16, dtype='short'; % signed 16-bit case 24, dtype='bit24'; % signed 24-bit case 32, dtype='float'; % normalized 32-bit floating point otherwise, err = 'Invalid number of bits specified.'; return; end % Write data, one row at a time (one sample from each channel): [samples,channels] = size(data); total_samples = samples*channels; if (fwrite(fid, reshape(data',total_samples,1), dtype) ~= total_samples), err = 'Failed to write PCM data samples.'; return; end % Determine # bytes/sample - format requires rounding % to next integer number of bytes: BytesPerSample = ceil(fmt.nBitsPerSample/8); % Determine if a pad-byte must be appended to data chunk: if rem(total_samples*BytesPerSample, 2) ~= 0, fwrite(fid,0,'uchar'); end else % Unknown wave-format for data. err = 'Unsupported data format.'; end return % end of wavwrite.m
github
robical/BlindSourceSeparation-master
OLAfft.m
.m
BlindSourceSeparation-master/OLAfft.m
1,047
utf_8
86f0ef14501a48d7746ebec4b9055b70
%&Implementazione STFT % % av=percentuale di avanzamento espressa in forma decimale es. 50%=0.5 % win=tipo di finestra function [fourier1]=OLAfft(signal1,win,av) durata=length(signal1); %durata segnale pas=length(win); %durata finestra splice1=zeros(pas,(fix(durata/(pas*av)))+1); part1=zeros(pas,(fix(durata/(pas*av)))+1); splice1(1:pas,1)=signal1(1:pas,1)'.*win'; part1(1:pas,1)=splice1(1:pas,1); cicli=fix((durata-pas)/(pas/2)); for i=2:cicli; start=1+(i-1)*(pas*av); %avanza del 50% fin=start+pas-1; part1(1:pas,i)=signal1(start:fin,1); splice1(1:pas,i)=part1(1:pas,i)'.*win'; end; resto=rem(durata,(pas*av)); fin=fix(durata/(pas*av))*(pas*av); part1(1:pas,(fix(durata/(pas*av))-1))=[signal1(fin:durata,1); zeros((pas-resto-1),1)]; splice1(1:pas,(fix(durata/(pas*av))-1))=part1(1:pas,(fix(durata/(pas*av))-1))'.*win'; for i=1:fix(durata/(pas*av))-1; fourier1(1:pas,i)=fftshift(fft(splice1(1:pas,i))); end;
github
robical/BlindSourceSeparation-master
wavexread.m
.m
BlindSourceSeparation-master/img/Progetto/wavexread.m
20,102
utf_8
f35f68e29ec4b1545c1597f333b27469
function [y,Fs,nbits,speakers] = wavexread(file,ext) %WAVEXREAD Read Microsoft WAVE-FORMAT-EXTENSIBLE (".wav") sound file. % Y=WAVEXREAD(FILE) reads a WAVE file specified by the string FILE, % returning the sampled data in Y. The ".wav" extension is appended % if no extension is given. Amplitude values are in the range [-1,+1]. % % [Y,FS,NBITS]=WAVEXREAD(FILE) returns the sample rate (FS) in Hertz % and the number of bits per sample (NBITS) used to encode the % data in the file. % % [...]=WAVEXREAD(FILE,N) returns only the first N samples from each % channel in the file. % [...]=WAVEXREAD(FILE,[N1 N2]) returns only samples N1 through N2 from % each channel in the file. % SIZ=WAVEXREAD(FILE,'size') returns the size of the audio data contained % in the file in place of the actual audio data, returning the % vector SIZ=[samples channels]. % % [Y,FS,NBITS,OPTS]=WAVEXREAD(...) returns a structure OPTS of additional % information contained in the WAV file. The content of this % structure differs from file to file. Typical structure fields % include '.fmt' (audio format information) and '.info' (text % which may describe subject title, copy right, etc.) % % Supports multi-channel data, with up to 32 bits per sample. % % NOTE: This file reader only supports Microsoft PCM data format. % It does not support wave-list data. % % See also WAVEXWRITE, WAVWRITE, AUREAD, AUWRITE. % Author: D. Orofino % Copyright 1984-2002 The MathWorks, Inc. % $Revision: 5.28 $ $Date: 2002/05/30 20:42:03 $ % % Modified 2004/07/27 by Sylvain Choisel % to handle WAVE-FORMAT-EXTENSIBLE % Parse input arguments: nargchk(1,2,nargin); if nargin<2, ext=[]; end % Default - read all samples exts = prod(size(ext)); % length of extent info if ~strncmpi(ext,'size',exts) & (exts > 2), error('Index range must be specified as a scalar or 2-element vector.'); end if ~ischar(ext) & exts==1, if ext==0, ext='size'; % synonym for size else ext=[1 ext]; % Prepend start sample index end end % Open WAV file: [fid,msg] = open_wav(file); error(msg); % Now the file is open - wrap remaining code in try/catch so we can % close the file if an error occurs try % Find the first RIFF chunk: [riffck,msg] = find_cktype(fid,'RIFF'); %error(msg); if ~isempty(msg), error('Not a WAVE file.'); end % Verify that RIFF file is WAVE data type: msg = check_rifftype(fid,'WAVE'); error(msg); % Find optional chunks, and don't stop till <data-ck> found: found_data = 0; end_of_file = 0; opt_ck = []; while(~end_of_file), [ck,msg] = find_cktype(fid); error(msg); switch lower(ck.ID) case 'end of file' end_of_file = 1; case 'fmt' % <fmt-ck> found [opt_ck,msg] = read_wavefmt(fid,ck,opt_ck); error(msg); case 'data' % <data-ck> found: found_data = 1; if ~isfield(opt_ck,'fmt'), error('Corrupt WAV file: found audio data before format information.'); end if strncmpi(ext,'size',exts) | ... (~isempty(ext) & all(ext==0)), % Caller doesn't want data - just data size: [samples,msg] = read_wavedat(ck, opt_ck.fmt, -1); error(msg); y = [samples opt_ck.fmt.nChannels]; else % Read <wave-data>: [datack,msg] = read_wavedat(ck, opt_ck.fmt, ext); error(msg); y = datack.Data; end case 'fact' % Optional <fact-ck> found: [opt_ck,msg] = read_factck(fid, ck, opt_ck); error(msg); case 'disp' % Optional <disp-ck> found: [opt_ck,msg] = read_dispck(fid, ck, opt_ck); error(msg); case 'list' % Optional <list-ck> found: [opt_ck, msg] = read_listck(fid, ck, opt_ck); error(msg); otherwise % Skip over data in unprocessed chunks: if rem(ck.Size,2), ck.Size=ck.Size+1; end if(fseek(fid,ck.Size,0)==-1), error('Incorrect chunk size information in WAV file.'); end end end catch fclose(fid); error(lasterr); end fclose(fid); % Parse structure info for return to user: Fs = opt_ck.fmt.nSamplesPerSec; if opt_ck.fmt.wFormatTag == 1 | opt_ck.fmt.wFormatTag == 3, % Type 3 floating point has no nBitsPerSample field, so use % nBlockAlign to figure out number of bits nbits = (opt_ck.fmt.nBlockAlign / opt_ck.fmt.nChannels) * 8; else nbits = []; % Unknown end speakers=find((fliplr(dec2bin(opt_ck.fmt.dwChanelMask)-48))~=0); % end of wavread() % ------------------------------------------------------------------------ % Local functions: % ------------------------------------------------------------------------ % --------------------------------------------- % OPEN_WAV: Open a WAV file for reading % --------------------------------------------- function [fid,msg] = open_wav(file) % Append .wav extension if it's missing: [pat,nam,ext] = fileparts(file); if isempty(ext), file = [file '.wav']; end [fid,msg] = fopen(file,'rb','l'); % Little-endian if fid == -1, msg = 'Cannot open file.'; end return % --------------------------------------------- % READ_CKINFO: Reads next RIFF chunk, but not the chunk data. % If optional sflg is set to nonzero, reads SUBchunk info instead. % Expects an open FID pointing to first byte of chunk header. % Returns a new chunk structure. % --------------------------------------------- function [ck,msg] = read_ckinfo(fid) msg = ''; ck.fid = fid; ck.Data = []; err_msg = 'Truncated chunk header found - possibly not a WAV file.'; [s,cnt] = fread(fid,4,'char'); % Do not error-out if a few (<4) trailing chars are in file % Just return quickly: if (cnt~=4), if feof(fid), % End of the file (not an error) ck.ID = 'end of file'; % unambiguous chunk ID (>4 chars) ck.Size = 0; else msg = err_msg; end return end ck.ID = deblank(setstr(s')); % Read chunk size (skip if subchunk): [sz,cnt] = fread(fid,1,'ulong'); if cnt~=1, msg = err_msg; return end ck.Size = sz; return % --------------------------------------------- % FIND_CKTYPE: Finds a chunk with appropriate type. % Searches from current file position specified by fid. % Leaves file positions to data of desired chunk. % If optional sflg is set to nonzero, finds a SUBchunk instead. % --------------------------------------------- function [ck,msg] = find_cktype(fid,ftype) msg = ''; if nargin<2, ftype = ''; end [ck,msg] = read_ckinfo(fid); if ~isempty(msg), return; end % Was a required chunk type specified? if ~isempty(ftype) & ~strcmpi(ck.ID,ftype), msg = ['<' ftype '-ck> did not appear as expected']; end return % --------------------------------------------- % CHECK_RIFFTYPE: Finds the RIFF data type. % Searches from current file position specified by fid. % Leaves file positions to data of desired chunk. % --------------------------------------------- function msg = check_rifftype(fid,ftype) msg = ''; [rifftype,cnt] = fread(fid,4,'char'); rifftype = setstr(rifftype)'; if cnt~=4, msg = 'Not a WAVE file.'; elseif ~strcmpi(rifftype,ftype), msg = ['File does not contain required ''' ftype ''' data chunk.']; end return % --------------------------------------------- % READ_LISTCK: Read the FLIST chunk: % --------------------------------------------- function [opt_ck,msg] = read_listck(fid,ck, orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 4; % # of required bytes in <list-ck> header msg = ''; err_msg = 'Error reading <list-ck> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <list-ck> data: listdata = setstr(fread(fid,total_bytes,'uchar')'); listtype = lower(listdata(1:4)); % Get LIST type listdata = listdata(5:end); % Move past INFO if strcmp(listtype,'info'), % Information: while(~isempty(listdata)), id = listdata(1:4); switch lower(id) case 'iart' name = 'Artist'; case 'icmt' name = 'Comments'; case 'icrd' name = 'Creation date'; case 'icop' name = ['Copy' 'right']; case 'ieng' name = 'Engineer'; case 'inam' name = 'Name'; case 'iprd' name = 'Product'; case 'isbj' name = 'Subject'; case 'isft' name = 'Software'; case 'isrc' name = 'Source'; otherwise name = id; end if ~isfield(opt_ck,'info'), opt_ck.info = []; end len = listdata(5:8) * 2.^[0 8 16 24]'; txt = listdata(9:9+len-1); % Fix up text: deblank, and replace CR/LR with LF txt = deblank(txt); idx=findstr(txt,setstr([13 10])); txt(idx) = ''; % Store - don't include the "name" info opt_ck.info.(lower(id)) = txt; if rem(len,2), len=len+1; end listdata = listdata(9+len:end); end else if ~isfield(opt_ck,'list'), opt_ck.list = []; end opt_ck.list.(listtype) = listdata; end % Skip over any unprocessed data: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - (ftell(fid) - orig_pos); if rbytes~=0, if (fseek(fid,rbytes,'cof')==-1), msg = err_msg; end end return % --------------------------------------------- % READ_DISPCK: Read the DISP chunk: % --------------------------------------------- function [opt_ck, msg] = read_dispck(fid,ck,orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 4; % # of required bytes in <disp-ck> header msg = ''; err_msg = 'Error reading <disp-ck> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <disp-ck> data: data = fread(fid,total_bytes,'uchar'); % Process data: % First few entries are size info: icon_data = data; siz_info = reshape(icon_data(1:2*4),4,2)'; siz_info = siz_info*(2.^[0 8 16 24]'); is_icon = isequal(siz_info,[8;40]); if ~is_icon, % Not the icon: opt_ck.disp.name = 'DisplayName'; txt = deblank(setstr(data(5:end)')); opt_ck.disp.text = txt; end % Skip over any unprocessed data: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - (ftell(fid) - orig_pos); if rbytes~=0, if(fseek(fid,rbytes,'cof')==-1), msg = err_msg; end end return % --------------------------------------------- % READ_FACTCK: Read the FACT chunk: % --------------------------------------------- function [opt_ck,msg] = read_factck(fid,ck,orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 4; % # of required bytes in <fact-ck> header msg = ''; err_msg = 'Error reading <fact-ck> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <fact-ck> data: opt_ck.fact = setstr(fread(fid,total_bytes,'uchar')'); % Skip over any unprocessed data: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - (ftell(fid) - orig_pos); if rbytes~=0, if(fseek(fid,rbytes,'cof')==-1), msg = err_msg; end end return % --------------------------------------------- % READ_WAVEFMT: Read WAVE format chunk. % Assumes fid points to the <wave-fmt> subchunk. % Requires chunk structure to be passed, indicating % the length of the chunk in case we don't recognize % the format tag. % --------------------------------------------- function [opt_ck,msg] = read_wavefmt(fid,ck,orig_opt_ck) opt_ck = orig_opt_ck; orig_pos = ftell(fid); total_bytes = ck.Size; % # bytes in subchunk nbytes = 40; % # of required bytes in <wave-format> header msg = ''; err_msg = 'Error reading <wave-fmt> chunk.'; if total_bytes < nbytes, msg = err_msg; return end % Read standard <wave-format> data: opt_ck.fmt.wFormatTag = fread(fid,1,'ushort'); % Data encoding format opt_ck.fmt.nChannels = fread(fid,1,'ushort'); % Number of channels opt_ck.fmt.nSamplesPerSec = fread(fid,1,'ulong'); % Samples per second opt_ck.fmt.nAvgBytesPerSec = fread(fid,1,'ulong'); % Avg transfer rate opt_ck.fmt.nBlockAlign = fread(fid,1,'ushort'); % Block alignment %sc opt_ck.fmt.wBitsPerSample = fread(fid,1,'ushort'); opt_ck.fmt.cbSize = fread(fid,1,'ushort'); opt_ck.fmt.wValidBitsPerSample = fread(fid,1,'ushort'); opt_ck.fmt.dwChanelMask = fread(fid,1,'ulong'); opt_ck.fmt.subFormat = fread(fid,16,'uchar'); % Read format-specific info: switch opt_ck.fmt.wFormatTag case 1 % PCM Format: %[opt_ck.fmt, msg] = read_fmt_pcm(fid, ck, opt_ck.fmt); exit('Invalid extensible format'); case hex2dec('FFFE') % [opt_ck.fmt, msg] = read_fmt_pcm(fid, ck, opt_ck.fmt); end % Skip over any unprocessed fmt-specific data: %if rem(total_bytes,2), total_bytes=total_bytes+1; end %rbytes = total_bytes - (ftell(fid) - orig_pos); %if rbytes~=0, % if(fseek(fid,rbytes,'cof')==-1), % msg = err_msg; % end %end return % --------------------------------------------- % READ_FMT_PCM: Read <PCM-format-specific> info % --------------------------------------------- function [fmt,msg] = read_fmt_pcm(fid, ck, fmt) % There had better be a bits/sample field: total_bytes = ck.Size; % # bytes in subchunk nbytes = 14; % # of bytes already read in <wave-format> header msg = ''; err_msg = 'Error reading PCM <wave-fmt> chunk.'; %if (total_bytes < nbytes+2), % msg = err_msg; % return %end %[bits,cnt] = fread(fid,1,'ushort'); %nbytes=nbytes+2; %if (cnt~=1), % msg = err_msg; % return %end %fmt.nBitsPerSample=bits; % Are there any additional fields present? if (total_bytes > nbytes), % See if the "cbSize" field is present. If so, grab the data: if (total_bytes >= nbytes+2), % we have the cbSize ushort in the file: [cbSize,cnt]=fread(fid,1,'ushort'); nbytes=nbytes+2; if (cnt~=1), msg = err_msg; return end fmt.cbSize = cbSize; end % Simply skip any remaining stuff - we don't know what it is: if rem(total_bytes,2), total_bytes=total_bytes+1; end rbytes = total_bytes - nbytes; if rbytes~=0, if (fseek(fid,rbytes,'cof') == -1); msg = err_msg; end end end return % --------------------------------------------- % READ_WAVEDAT: Read WAVE data chunk % Assumes fid points to the wave-data chunk % Requires <data-ck> and <wave-format> structures to be passed. % Requires extraction range to be specified. % Setting ext=[] forces ALL samples to be read. Otherwise, % ext should be a 2-element vector specifying the first % and last samples (per channel) to be extracted. % Setting ext=-1 returns the number of samples per channel, % skipping over the sample data. % --------------------------------------------- function [dat,msg] = read_wavedat(datack,wavefmt,ext) % In case of unsupported data compression format: dat = []; fmt_msg = ''; switch wavefmt.wFormatTag case 1 % PCM Format: [dat,msg] = read_dat_pcm(datack,wavefmt,ext); case 2 fmt_msg = 'Microsoft ADPCM'; case 3 % normalized floating-point [dat,msg] = read_dat_pcm(datack,wavefmt,ext); case 6 fmt_msg = 'CCITT a-law'; case 7 fmt_msg = 'CCITT mu-law'; case 17 fmt_msg = 'IMA ADPCM'; case 34 fmt_msg = 'DSP Group TrueSpeech TM'; case 49 fmt_msg = 'GSM 6.10'; case 50 fmt_msg = 'MSN Audio'; case 257 fmt_msg = 'IBM Mu-law'; case 258 fmt_msg = 'IBM A-law'; case 259 fmt_msg = 'IBM AVC Adaptive Differential'; case hex2dec('FFFE') %sc % WAVE-FORMAT-EXTENSIBLE [dat,msg] = read_dat_pcm(datack,wavefmt,ext); otherwise fmt_msg = ['Format #' num2str(wavefmt.wFormatTag)]; end if ~isempty(fmt_msg), msg = ['Data compression format (' fmt_msg ') is not supported.']; end return % --------------------------------------------- % READ_DAT_PCM: Read PCM format data from <wave-data> chunk. % Assumes fid points to the wave-data chunk % Requires <data-ck> and <wave-format> structures to be passed. % Requires extraction range to be specified. % Setting ext=[] forces ALL samples to be read. Otherwise, % ext should be a 2-element vector specifying the first % and last samples (per channel) to be extracted. % Setting ext=-1 returns the number of samples per channel, % skipping over the sample data. % --------------------------------------------- function [dat,msg] = read_dat_pcm(datack,wavefmt,ext) dat = []; msg = ''; % Determine # bytes/sample - format requires rounding % to next integer number of bytes: BytesPerSample = ceil(wavefmt.nBlockAlign / wavefmt.nChannels); if (BytesPerSample == 1), dtype='uchar'; % unsigned 8-bit elseif (BytesPerSample == 2), dtype='short'; % signed 16-bit elseif (BytesPerSample == 3) dtype='bit24'; % signed 24-bit elseif (BytesPerSample == 4), % 32-bit 16.8 float (type 1 - 32-bit) % 32-bit normalized floating point dtype = 'float'; % 32-bit 24.0 float (type 1 - 24-bit) if wavefmt.wFormatTag ~= 3 & wavefmt.nBitsPerSample == 24, BytesPerSample = 3; end else msg = 'Cannot read PCM file formats with more than 32 bits per sample.'; return end total_bytes = datack.Size; % # bytes in this chunk total_samples = total_bytes / BytesPerSample; SamplesPerChannel = total_samples / wavefmt.nChannels; if ~isempty(ext) & ext==-1, % Just return the samples per channel, and fseek past data: dat = SamplesPerChannel; % Add in a pad-byte, if required: total_bytes = total_bytes + rem(datack.Size,2); if(fseek(datack.fid,total_bytes,'cof')==-1), msg = 'Error reading PCM file format.'; end return end % Determine sample range to read: if isempty(ext), ext = [1 SamplesPerChannel]; % Return all samples else if prod(size(ext))~=2, msg = 'Sample limit vector must have 2 elements.'; return end if ext(1)<1 | ext(2)>SamplesPerChannel, msg = 'Sample limits out of range.'; return end if ext(1)>ext(2), msg = 'Sample limits must be given in ascending order.'; return end end bytes_remaining = total_bytes; % Preset byte counter % Skip over leading samples: if ext(1)>1, % Skip over leading samples, if specified: skipcnt = BytesPerSample * (ext(1)-1) * wavefmt.nChannels; if(fseek(datack.fid, skipcnt,'cof') == -1), msg = 'Error reading PCM file format.'; return end % % Update count of bytes remaining: bytes_remaining = bytes_remaining - skipcnt; end % Read desired data: nSPCext = ext(2)-ext(1)+1; % # samples per channel in extraction range dat = datack; % Copy input structure to output extSamples = wavefmt.nChannels*nSPCext; dat.Data = fread(datack.fid, [wavefmt.nChannels nSPCext], dtype); % % Update count of bytes remaining: skipcnt = BytesPerSample*nSPCext*wavefmt.nChannels; bytes_remaining = bytes_remaining - skipcnt; % if cnt~=extSamples, dat='Error reading file.'; return; end % Skip over trailing samples: if(fseek(datack.fid, BytesPerSample * ... (SamplesPerChannel-ext(2))*wavefmt.nChannels, 'cof')==-1), msg = 'Error reading PCM file format.'; return end % Update count of bytes remaining: skipcnt = BytesPerSample*(SamplesPerChannel-ext(2))*wavefmt.nChannels; bytes_remaining = bytes_remaining - skipcnt; % Determine if a pad-byte is appended to data chunk, % skipping over it if present: if rem(datack.Size,2), fseek(datack.fid, 1, 'cof'); end % Rearrange data into a matrix with one channel per column: dat.Data = dat.Data'; % Normalize data range: min will hit -1, max will not quite hit +1. if BytesPerSample==1, dat.Data = (dat.Data-128)/128; % [-1,1) elseif BytesPerSample==2, dat.Data = dat.Data/32768; % [-1,1) elseif BytesPerSample==3, dat.Data = dat.Data/(2^23); % [-1,1) elseif BytesPerSample==4, if wavefmt.wFormatTag ~= 3, % Type 3 32-bit is already normalized dat.Data = dat.Data/32768; % [-1,1) end end return % end of wavread.m
github
robical/BlindSourceSeparation-master
STFT.m
.m
BlindSourceSeparation-master/img/Progetto/STFT.m
560
utf_8
c29454de99da3167b1a34b11c3ac81a9
%STFT % CALCOLO DEL NUMERO DI SPLICE: % numero_splice=1+((length(signal)-length(win))/(length(win)/2)) % % function [trasf]=STFT(signal,win) M=length(win); R=M/2; %hop size del 50% (M/2) part(1:M,1)=signal(1:M,1); splice(1:M,1)=part(1:M,1)'.*win'; cicli=fix((length(signal)-length(win))/(length(win)/2)); %2 o 4 for i=2:cicli; start=1+(i-1)*(R); fin=start+length(win)-1; part(1:M,i)=signal(start:fin,1); splice(1:M,i)=part(1:M,i)'.*win'; end; for i=1:(size(splice,2)); trasf(1:M,i)=fft(splice(1:M,i)); end;
github
robical/BlindSourceSeparation-master
wavexwrite.m
.m
BlindSourceSeparation-master/img/Progetto/wavexwrite.m
8,855
utf_8
5e65dd381efc54d3f9865c9c79100c35
function wavexwrite(y,Fs,nbits,wavefile,speakers) %WAVEXWRITE Write WAVE_FORMAT_EXTENSIBLE sound file. % WAVEXWRITE(Y,FS,NBITS,WAVEFILE, SPEAKERS) writes data Y to a WAVEX % file specified by the file name WAVEFILE, with a sample rate % of FS Hz and with NBITS number of bits. NBITS must be 8, 16, % 24, or 32. Stereo data should be specified as a matrix with two % columns. For NBITS < 32, amplitude values outside the range % [-1,+1] are clipped. % % SPEAKERS is a vector of speaker numbers % e.g. [1,2] for stereo % [1:5] for 5.1 % [3] for center channel % % WAVEXWRITE(Y,FS,WAVEFILE) assumes NBITS=16 bits. % WAVEXWRITE(Y,WAVEFILE) assumes NBITS=16 bits and FS=44100 Hz. % % 8-, 16-, and 24-bit files are type 1 integer PCM. 32-bit files % are written as type 3 normalized floating point. % % Modified 2004/07/27 by Sylvain Choisel % to handle WAVE-FORMAT-EXTENSIBLE % email: [email protected] % Parse inputs: error(nargchk(2,5,nargin)); if nargin < 3, wavefile = Fs; Fs = 44100; nbits = 16; elseif nargin < 4, wavefile = nbits; nbits = 16; end % If input is a vector, force it to be a column: if ndims(y) > 2, error('Data array cannot be an N-D array.'); end if size(y,1)==1, y = y(:); end [samples, channels] = size(y); if nargin < 5, speakerMask=2^channels-1; else if (length(speakers)~=channels) error ('Speaker mask length must be equal to the number of channels'); end speakerMask=sum(2.^(speakers-1)); end % Determine number of bytes in chunks % (not including pad bytes, if needed): % ---------------------------------- % 'RIFF' 4 bytes % size 4 bytes (ulong) % 'WAVE' 4 bytes % 'fmt ' 4 bytes % size 4 bytes (ulong) % <wave-format> 14 bytes % <format_specific> 2 bytes (PCM) % 'data' 4 bytes % size 4 bytes (ulong) % <wave-data> N bytes % ---------------------------------- bytes_per_sample = ceil(nbits/8); total_samples = samples * channels; total_bytes = total_samples * bytes_per_sample; riff_cksize = 4+48+total_bytes; % Don't include 'RIFF' or its size field fmt_cksize = 40; % Don't include 'fmt ' or its size field data_cksize = total_bytes; % Don't include 'data' or its size field % Determine pad bytes: data_pad = rem(data_cksize,2); riff_cksize = riff_cksize + data_pad; % + fmt_pad, always 0 % Open file for output: [fid,err] = OpenWaveWrite(wavefile); error(err); % Prepare basic chunk structure fields: ck=[]; ck.fid=fid; ck.filename = wavefile; % Write RIFF chunk: ck.ID = 'RIFF'; ck.Size = riff_cksize; error(write_ckinfo(ck)); % Write WAVE subchunk: ck.ID = 'WAVE'; ck.Size = []; % Indicate a subchunk (no chunk size) error(write_ckinfo(ck)); % Write <fmt-ck>: ck.ID = 'fmt '; ck.Size = fmt_cksize; error(write_ckinfo(ck)); % Write <wave-format>: fmt.filename = wavefile; fmt.wFormatTag = hex2dec('FFFE'); fmt.nChannels = channels; % Number of channels fmt.nSamplesPerSec = Fs; % Samples per second fmt.nAvgBytesPerSec = channels*bytes_per_sample*Fs; % Avg transfer rate fmt.nBlockAlign = channels*bytes_per_sample; % Block alignment fmt.nBitsPerSample = 8*bytes_per_sample; fmt.cbSize = 22; fmt.wValidBitsPerSample = nbits; fmt.dwSpkMask = speakerMask; fmt.subFormat = [1 0 0 0 0 0 16 0 8*16 0 0 hex2dec('AA') 0 hex2dec('38') hex2dec('9B') hex2dec('71')]; error(write_wavefmt(fid,fmt)); % Write <data-ck>: ck.ID = 'data'; ck.Size = data_cksize; error(write_ckinfo(ck)); % Write <wave-data>, and its pad byte if needed: error(write_wavedat(fid,fmt,y)); % Close file: fclose(fid); % end of wavwrite() % ------------------------------------------------------------------------ % Private functions: % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ function [fid,err] = OpenWaveWrite(wavefile) % OpenWaveWrite % Open WAV file for writing. % If filename does not contain an extension, add ".wav" fid = []; err = ''; if ~isstr(wavefile), err='Wave file name must be a string.'; return; end % modified 27/07/2004 sc %if isempty(findstr(wavefile,'.')), % wavefile=[wavefile '.wav']; %end [pathstr,name,ext,versn]=fileparts(wavefile); if (~strcmp(lower(ext),'.wav')) wavefile=[wavefile '.wav']; end % Open file, little-endian: [fid,err] = fopen(wavefile,'wb','l'); return % ------------------------------------------------------------------------ function err = write_ckinfo(ck) % WRITE_CKINFO: Writes next RIFF chunk, but not the chunk data. % Assumes the following fields in ck: % .fid File ID to an open file % .ID 4-character string chunk identifier % .Size Size of chunk (empty if subchunk) % % % Expects an open FID pointing to first byte of chunk header, % and a chunk structure. % ck.fid, ck.ID, ck.Size, ck.Data errmsg = ['Failed to write ' ck.ID ' chunk to WAVE file: ' ck.filename]; err = ''; if (fwrite(ck.fid, ck.ID, 'char') ~= 4), err=errmsg; return; end if ~isempty(ck.Size), % Write chunk size: if (fwrite(ck.fid, ck.Size, 'ulong') ~= 1), err=errmsg; return; end end return % ------------------------------------------------------------------------ function err = write_wavefmt(fid, fmt) % WRITE_WAVEFMT: Write WAVE format chunk. % Assumes fid points to the wave-format subchunk. % Requires chunk structure to be passed, indicating % the length of the chunk. errmsg = ['Failed to write WAVE format chunk to file' fmt.filename]; err = ''; % Create <wave-format> data: if (fwrite(fid, fmt.wFormatTag, 'ushort') ~= 1) | ... (fwrite(fid, fmt.nChannels, 'ushort') ~= 1) | ... (fwrite(fid, fmt.nSamplesPerSec, 'ulong' ) ~= 1) | ... (fwrite(fid, fmt.nAvgBytesPerSec, 'ulong' ) ~= 1) | ... (fwrite(fid, fmt.nBlockAlign, 'ushort') ~= 1) | ... (fwrite(fid, fmt.nBitsPerSample, 'ushort') ~= 1) | ... (fwrite(fid, fmt.cbSize, 'ushort') ~= 1) | ... (fwrite(fid, fmt.wValidBitsPerSample, 'ushort') ~= 1) | ... (fwrite(fid, fmt.dwSpkMask, 'ulong' ) ~= 1) | ... (fwrite(fid, fmt.subFormat, 'uchar' ) ~= 16) err=errmsg; end return % ----------------------------------------------------------------------- function y = PCM_Quantize(x, fmt) % PCM_Quantize: % Scale and quantize input data, from [-1, +1] range to % either an 8-, 16-, or 24-bit data range. % Clip data to normalized range [-1,+1]: ClipMsg = ['Data clipped during write to file:' fmt.filename]; ClipWarn = 0; % Determine slope (m) and bias (b) for data scaling: nbits = fmt.nBitsPerSample; m = 2.^(nbits-1); switch nbits case 8, b=128; case {16,24}, b=0; otherwise, error('Invalid number of bits specified.'); end y = round(m .* x + b); % Determine quantized data limits, based on the % presumed input data limits of [-1, +1]: ylim = [-1 +1]; qlim = m * ylim + b; qlim(2) = qlim(2)-1; % Clip data to quantizer limits: i = find(y < qlim(1)); if ~isempty(i), warning(ClipMsg); ClipWarn=1; y(i) = qlim(1); end i = find(y > qlim(2)); if ~isempty(i), if ~ClipWarn, warning(ClipMsg); end y(i) = qlim(2); end return % ----------------------------------------------------------------------- function err = write_wavedat(fid,fmt,data) % WRITE_WAVEDAT: Write WAVE data chunk % Assumes fid points to the wave-data chunk % Requires <wave-format> structure to be passed. err = ''; if fmt.wFormatTag==1 | fmt.wFormatTag==3 | fmt.wFormatTag==hex2dec('FFFE'), % PCM Format % 32-bit Type 3 is normalized, so no scaling needed. if fmt.nBitsPerSample ~= 32, data = PCM_Quantize(data, fmt); end switch fmt.nBitsPerSample case 8, dtype='uchar'; % unsigned 8-bit case 16, dtype='short'; % signed 16-bit case 24, dtype='bit24'; % signed 24-bit case 32, dtype='float'; % normalized 32-bit floating point otherwise, err = 'Invalid number of bits specified.'; return; end % Write data, one row at a time (one sample from each channel): [samples,channels] = size(data); total_samples = samples*channels; if (fwrite(fid, reshape(data',total_samples,1), dtype) ~= total_samples), err = 'Failed to write PCM data samples.'; return; end % Determine # bytes/sample - format requires rounding % to next integer number of bytes: BytesPerSample = ceil(fmt.nBitsPerSample/8); % Determine if a pad-byte must be appended to data chunk: if rem(total_samples*BytesPerSample, 2) ~= 0, fwrite(fid,0,'uchar'); end else % Unknown wave-format for data. err = 'Unsupported data format.'; end return % end of wavwrite.m