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
jacksky64/imageProcessing-master
GUI_18.m
.m
imageProcessing-master/Matlab UI Examples/GUI_18.m
1,578
utf_8
5d1b116654e9c8c8c45890b3afb9fa45
function [] = GUI_18() % Demonstrate the use of the buttondownfcn for an axes. % Clicking on the axes creates a random line. Note that clicking on the % line does the same thing. This must be accounted for in the coding % below, or clicking on the line would do nothing. Right click to delete % the line. % % An exercise would be to alter the code so that right clicking recreates % the plot in another figure window. This could be done at least two % different ways. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[200 200 200 200],... 'menubar','none',... 'numbertitle','off',... 'name','GUI_18',... 'resize','off'); S.ax = axes('units','pixels',... 'position',[30 30 160 160],... 'fontsize',8,... 'buttondownfcn',{@ax_bdfcn,S},... 'nextplot','replacechildren'); function [] = ax_bdfcn(varargin) % buttondownfcn for axes. [h,S] = varargin{[1,3]}; % Extract the calling handle and structure. % We need to account for when the user clicks the line instead of the axes. if ~strcmpi(get(h,'type'),'axes') h = findobj('children',h); % end seltype = get(S.fh,'selectiontype'); % Right-or-left click? switch seltype case 'alt' cla % Delete the line. case 'normal' ln = plot(h,sort(rand(1,10))); % Plot a new line. set(ln,'buttondownfcn',{@ax_bdfcn,S}) otherwise % Do something else for double-clicks, etc. end
github
jacksky64/imageProcessing-master
GUI_35.m
.m
imageProcessing-master/Matlab UI Examples/GUI_35.m
4,421
utf_8
1f9c2d3cb5f59e45e51321458670ffdd
function [] = GUI_35() % Demonstrate how to use toggle buttons to mimic tabbed panels. % Creates a GUI with three toggle buttons which act as tabs. One of the % tabs is not selectable until the user plots a random quartic by % pressing the pushbutton at the bottom of the screen. The middle tab % shows the result of fitting (with polyfit) a polynomial to the "unknown" % quartic. % % Suggested exercise: Add another tab which contains help info for how to % use the GUI. % % % Author: Matt Fig % Date: 7/15/2009 SCR = get(0,'Screensize'); % Get screensize. S.fh = figure('numbertitle','off',... 'menubar','none',... 'units','pixels',... 'position',[SCR(3)/2-200 ,SCR(4)/2-200 , 400, 400],... 'name','GUI_35',... 'resize','off'); S.ax = axes('units','pixels',... 'position',[50 100 300 230]); S.pb1 = uicontrol('style','pushbutton',... 'units','pixels',... 'position',[50 20 300 40],... 'string','Plot Random Quartic Polynomial',... 'fontsize',12); % Toggles will act as the tabs. S.tg(1) = uicontrol('style','toggle',... 'units','pixels',... 'position',[5 355 60 40],... 'string','PLOT',... 'val',1); S.tg(2) = uicontrol('style','toggle',... 'units','pixels',... 'position',[65 355 60 40],... 'string','FIT',... 'value',0,... 'enable','off'); S.tg(3) = uicontrol('style','toggle',... 'units','pixels',... 'position',[125 355 60 40],... 'string','ABOUT',... 'value',0,... 'enable','on'); S.tx = uicontrol('style','text',... 'units','pixels',... 'position',[20 20 360 300],... 'visible','off',... 'string',{' ','This is a GUI with', 'fake tabs.',... 'Hope you enjoy.',' ',' ','Copyright:',... 'Matt Fig 2009'},... 'fontsize',20,'fontweight','bold'); W = {'style','edit','units','pixels','position'}; % Save some typing. S.ed(5) = uicontrol(W{:},[50 100 300 30]); S.ed(4) = uicontrol(W{:},[50 140 300 30]); S.ed(3) = uicontrol(W{:},[50 180 300 30]); S.ed(2) = uicontrol(W{:},[50 220 300 30]); S.ed(1) = uicontrol(W{:},[50 260 300 30]); % Set remaining properties. set(S.pb1,'callback',{@pb_call,S}) % Set the callbacks. set(S.tg(:),{'callback'},{{@tg_call,S}}) set(S.ed(:),'visible','off','fontsize',12,'fontweight','bold',... 'backgroundcolor',[1 1 1]) function [] = pb_call(varargin) % Callback for pushbutton. x = -10:.1:10; % For the plot. plot(x,polyval(-5 + ceil(rand(1,5)*7),x)); % Plot some random quartic set(varargin{3}.tg(2),'enable','on'); % Turn on 'Fit' tab. function [] = tg_call(varargin) % Callback for togglebuttons. [h,S] = varargin{[1,3]}; % Get calling handle ans structure. if get(h,'val')==0 % Here the Toggle is already pressed. set(h,'val',1) % To keep the Tab-like functioning. end L = get(S.ax,'children'); % The line object. % Each case of the switch has one toggle associated with it. When a toggle % is selected the uicontrols which belong to it are made visible, and the % others are made invisible. This way each toggle has, in effect, its own % GUI. All uicontrols are part of the main GUI, some are simply hidden % when each toggle is selected. This mimics the action of tabs. switch h case S.tg(1) set(S.tg([2,3]),'val',0) set([S.ax,S.pb1,L],{'visible'},{'on'}) set([S.ed(:);S.tx],{'visible'},{'off'}) case S.tg(2) set(S.tg([1,3]),{'val'},{0}) set(S.ed(:),{'visible'},{'on'}) set([S.ax,S.pb1,L,S.tx],{'visible'},{'off'}) STR = 'The x^0 coefficient is: '; p = round(polyfit(get(L,'xdata'),get(L,'ydata'),4)); for ii = 0:4 STR(7) = num2str(ii); set(S.ed(5-ii),'str',[STR,num2str(p(5-ii))]) end otherwise set(S.tg([1,2]),{'val'},{0}) set(S.tx,'visible','on') set([S.ax;S.pb1;L;S.ed(:)],{'visible'},{'off'}) end
github
jacksky64/imageProcessing-master
GUI_14.m
.m
imageProcessing-master/Matlab UI Examples/GUI_14.m
1,965
utf_8
47c5253f9a3e32cb1d5d9ed19d2aff91
function [] = GUI_14() % Demonstrate colored text in a listbox, & how extract user's choice. % Creates a listbox which has words of different colors. When the % pushbutton is pushed, the users choice is printed to the screen. % Notice the use of the 'listboxtop' property in the callback. % This does NOT work in version 6.5. % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 230 40],... 'menubar','none',... 'name','GUI_14',... 'numbertitle','off',... 'resize','off'); % We will get different colors by using HTML. STR = {'<HTML><FONT COLOR="#66FF66">Green</FONT></HTML>',... '<HTML><FONT COLOR="red">Red</FONT></HTML>',... '<HTML><FONT COLOR="blue">Blue</FONT></HTML>',... '<HTML><FONT COLOR="#FF00FF">Violet</FONT></HTML>',... '<HTML><FONT COLOR="black">Black</FONT></HTML>',... '<HTML><FONT COLOR="yellow">Yellow</FONT></HTML>'}; S.COL = {'Green','Red','Blue','Violet','Black','Yellow'}; % Lookup table. S.ls = uicontrol('style','list',... 'units','pix',... 'position',[10 10 90 25],... 'string', STR,... 'fontsize',14); S.pb = uicontrol('style','push',... 'units','pix',... 'posit',[120 10 100 25],... 'string', 'Print Choice',... 'fontsize',10,... 'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for pushbutton. Displays user's choice at command line. S = varargin{3}; % Get structure. % If the 'value' property was used below, the user's choice might not show % correctly if the selection was made with the arrows on the listbox. L = get(S.ls,'listboxtop'); % Get the user's choice. disp(['Your color choice is: ' S.COL{L}]) % Print to command line.
github
jacksky64/imageProcessing-master
GUI_24.m
.m
imageProcessing-master/Matlab UI Examples/GUI_24.m
2,382
utf_8
a24403d9b73017f965c99561a85505b5
function [] = GUI_24() % Demonstrate how to get data from one GUI to another (data passing). % Creates a GUI with an editbox and a pushbutton. When the user presses % the pushbutton, another GUI pops up with an editbox. Whatever is in the % editbox of the second GUI when the user hits return will be put into the % edit box of the first GUI. % % Suggested exercise: Alter the code to have the new GUI display whatever % text is in the editbox from the first GUI when the new GUI is created. % Even more advanced: Alter the code so that two new GUIs cannot be % launched simultaneously by pressing the pushbutton repeatedly. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[500 500 200 130],... 'menubar','none',... 'numbertitle','off',... 'name','GUI_24',... 'resize','off'); S.ed = uicontrol('style','edit',... 'units','pix',... 'position',[10 60 180 60],... 'string','Data'); S.pb = uicontrol('style','pushbutton',... 'units','pix',... 'position',[10 20 180 30],... 'string','Push to Get Data',... 'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for GUI_24 pushbutton. S = varargin{3}; % Get the structure. f = figure('units','pixels',... 'menubar','none',... 'position',[750 510 200 100]); % Create a new GUI. E = uicontrol('style','edit',... 'units','pixels',... 'position',[10 20 180 60],... 'string','Type something, press return.',... 'callback',{@E_call,varargin{3}}); uicontrol(E); % Allow user to simply hit return without typing anything. % If user closes GUI_24, close new one as well because it will error when % it tries to execute the callback otherwise. set(S.fh,'deletefcn',{@fig_delet,f}) function [] = E_call(varargin) % Callback for secondary GUI editbox. S = varargin{3}; % Get the structure. set(S.ed,'string',get(gcbo,'string')) % Set GUI_24 editbox string. close(gcbf) % Close secondary GUI. function [] = fig_delet(varargin) % Executes when user closes GUI_24. try delete(varargin{3}) catch % Do nothing. end
github
jacksky64/imageProcessing-master
GUI_29.m
.m
imageProcessing-master/Matlab UI Examples/GUI_29.m
1,693
utf_8
577601b33f7fb91dd9b5df82ed2c1ea9
function [] = GUI_29() % Demonstrate the use of a uicontrol to manipulate an axes from a GUI, % and how to link two figures to close together. % The slider here controls the extent of the x lims up to a certain point. % % Suggested exercise: Alter the code so that an axes handle could be passed % in as an argument. Or a two-slider GUI could be made that controls both % the x and y limits. Even more advanced: Allow the GUI to replot if the % limits go beyond current data. This would require another input % argument. % % % Author: Matt Fig % Date: 7/15/2009 % First create the figure and plot to manipulate with the slider. x = 0:.1:100; % Some simple data. Notice the data goes beyond xlim. f = figure; % This is the figure which has the axes to be controlled. ax = axes; % This axes will be controlled. plot(x,sin(x)); xlim([0,pi]); % Set the beginning x/y limits. ylim([-1,1]) % Now create the other GUI S.fh = figure('units','pixels',... 'position',[400 400 220 40],... 'menubar','none',... 'name','GUI_29',... 'numbertitle','off',... 'resize','off'); S.sl = uicontrol('style','slide',... 'unit','pixel',... 'position',[10 10 200 20],... 'min',1,'value',pi,'max',100,... 'callback',{@sl_call,ax},... 'deletefcn',{@delete,f}); set(f,'deletef',{@delete,S.fh}) % Closing one closes the other. function [] = sl_call(varargin) % Callback for the slider. [h ax] = deal(varargin{[1;3]}); % Get the calling handle and structure. set(ax,'xlim',[0 get(h,'val')],'ylim',[-1,1])
github
jacksky64/imageProcessing-master
GUI_28.m
.m
imageProcessing-master/Matlab UI Examples/GUI_28.m
2,253
utf_8
874f0e66c524f1f9599e157001065e7e
function [] = GUI_28() % Demonstrate uicontextmenu for an axes click. % Clicking on the axes plots a single point. After plotting as many points % as desired, the user may click in the axes to access two options % concerning the plotted points. % % Suggested exercise: Add another menu to the context menu which % exports the current plot into another figure then clears the GUI axes for % more playtime. % % % Author: Matt Fig % Date: 7/15/2009 S.ln = []; % This holds the handles to the points. S.fh = figure('units','pixels',... 'position',[200 200 500 500],... 'menubar','none',... 'name','GUI_28',... 'numbertitle','off',... 'resize','off'); S.ax = axes('xlim',[0 1],'ylim',[0 1]); title('Click to add points. Right click for options.','fontw','bold') S.cm = uicontextmenu; S.um(1) = uimenu(S.cm,... 'label','Delete Points',... 'Callback', {@um1_call,S}); S.um(2) = uimenu(S.cm,... 'label','Rand Colors',... 'Callback', {@um2_call,S}); set(S.ax,'buttondownfcn',{@ax_bdfcn,S},'uicontextmenu',S.cm) function [] = ax_bdfcn(varargin) % Serves as the buttondownfcn for the axes. S = varargin{3}; % Get the structure. seltype = get(S.fh,'selectiontype'); % Right-or-left click? L = length(S.ln); if strmatch(seltype,'normal') p = get(S.ax, 'currentpoint'); % Get the position of the mouse. S.ln(L+1) = line(p(1),p(3),'Marker','+'); % Make our plot. set(S.ln(L+1),'uicontextmenu',S.cm) % So user can click a point too. end % Update structure. set(S.ax,'ButtonDownFcn',{@ax_bdfcn,S}) set(S.um(:),{'callback'},{{@um1_call,S};{@um2_call,S}}) function [] = um1_call(varargin) % Callback for uimenu to delete the points. S = varargin{3}; % Get the structure. delete(S.ln(:)); % Delete all the lines. S.ln = []; % And reset the structure. set(S.ax,'ButtonDownFcn',{@ax_bdfcn,S}) function [] = um2_call(varargin) % Callback for uimenu to change the colors of the points. S = varargin{3}; % Get the structure. L = length(S.ln); % The number of points. set(S.ln(:),{'color'},mat2cell(0+.75*rand(L,3),ones(1,L),3 )) % Color mat.
github
jacksky64/imageProcessing-master
UiMain.m
.m
imageProcessing-master/Matlab UI Examples/UiMain.m
7,463
utf_8
c3008a7b6fe35b399f8737898e26cc99
function varargout = UiMain(varargin) % UIMAIN MATLAB code for UiMain.fig % UIMAIN, by itself, creates a new UIMAIN or raises the existing % singleton*. % % H = UIMAIN returns the handle to a new UIMAIN or the handle to % the existing singleton*. % % UIMAIN('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in UIMAIN.M with the given input arguments. % % UIMAIN('Property','Value',...) creates a new UIMAIN or raises % the existing singleton*. Starting from the left, property value pairs are % applied to the GUI before UiMain_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to UiMain_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 UiMain % Last Modified by GUIDE v2.5 08-Mar-2014 16:52:07 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @UiMain_OpeningFcn, ... 'gui_OutputFcn', @UiMain_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 UiMain is made visible. function UiMain_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 UiMain (see VARARGIN) % Choose default command line output for UiMain handles.output = hObject; % Update handles structure guidata(hObject, handles); h=uitoolbar(hObject); uimenu(hObject); initialize_gui(hObject, handles, false); % UIWAIT makes UiMain wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = UiMain_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 calculate. function calculate_Callback(hObject, eventdata, handles) % hObject handle to calculate (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mass = handles.metricdata.samplePeriod; set(handles.mass, 'String', mass); % --- Executes on button press in reset. function reset_Callback(hObject, eventdata, handles) % hObject handle to reset (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) initialize_gui(gcbf, handles, true); % --- Executes when selected object changed in unitgroup. function unitgroup_SelectionChangeFcn(hObject, eventdata, handles) % hObject handle to the selected object in unitgroup % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if (hObject == handles.english) set(handles.text4, 'String', 'lb/cu.in'); set(handles.text5, 'String', 'cu.in'); set(handles.text6, 'String', 'lb'); else set(handles.text4, 'String', 'kg/cu.m'); set(handles.text5, 'String', 'cu.m'); set(handles.text6, 'String', 'kg'); end % -------------------------------------------------------------------- function initialize_gui(fig_handle, handles, isreset) % If the metricdata field is present and the reset flag is false, it means % we are we are just re-initializing a GUI by calling it from the cmd line % while it is up. So, bail out as we dont want to reset the data. if isfield(handles, 'metricdata') && ~isreset return; end handles.metricdata.samplePeriod = 8; % load GUI set(handles.samplePeriod, 'String', handles.metricdata.samplePeriod); set(handles.mass, 'String', 0); set(handles.unitgroup, 'SelectedObject', handles.english); set(handles.text4, 'String', 'us'); set(handles.text6, 'String', '#'); % Update handles structure guidata(handles.figure1, handles); function samplePeriod_Callback(hObject, eventdata, handles) % hObject handle to samplePeriod (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) samplePeriod = str2double(get(hObject, 'String')); if isnan(samplePeriod) set(hObject, 'String', 0); errordlg('Input must be a number','Error'); end % Save the new density value handles.metricdata.samplePeriod = samplePeriod; guidata(hObject,handles) % --- Executes during object creation, after setting all properties. function samplePeriod_CreateFcn(hObject, eventdata, handles) % hObject handle to samplePeriod (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 userfn1_Callback(hObject, eventdata, handles) % hObject handle to userfn1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Untitled_2_Callback(hObject, eventdata, handles) % hObject handle to Untitled_2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Untitled_3_Callback(hObject, eventdata, handles) % hObject handle to Untitled_3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Untitled_4_Callback(hObject, eventdata, handles) % hObject handle to Untitled_4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Untitled_5_Callback(hObject, eventdata, handles) % hObject handle to Untitled_5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
github
jacksky64/imageProcessing-master
GUI_27.m
.m
imageProcessing-master/Matlab UI Examples/GUI_27.m
2,495
utf_8
01b2f9b97ba9aa9827a2990eb59df25a
function [] = GUI_27() % Demonstrate how to display the current location of the mouse in an axes. % Run the GUI then move the cursor over the axes. The current location of % the pointer in the axes will be displayed at the top of the plot, in axes % units. % % Suggested exercise: Make this function to take an axes handle as an % input argument, automatically detect the xlim and ylim, and show the % pointer location in the title. Even more advanced: Detect when % the axes already has a title. In that case don't overwrite the title, % but launch another small GUI which displays the pointer location. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[560 528 560 420],... 'menubar','none',... 'name','GUI_27',... 'numbertitle','off',... 'resize','off'); % Now make a simple plot. x = 0:.1:2*pi; plot(x,sin(x)) S.ax = gca; set(S.ax,'unit','pix','position',[40 40 480 340]); axis([0 7 -1 1]) % Fill the structure with data. S.XLM = get(S.ax,'xlim'); S.YLM = get(S.ax,'ylim'); S.AXP = get(S.ax,'pos'); S.DFX = diff(S.XLM); S.DFY = diff(S.YLM); S.tx(1) = uicontrol('style','tex',... 'unit','pix',... 'posit',[50 390 250 20],... 'backg',get(S.fh,'color'),... 'fontsize',14,'fontweight','bold',... 'string','Current Pointer Location:'); % This textbox will display the current position of the mouse. S.tx(2) = uicontrol('style','tex',... 'unit','pix',... 'position',[310 390 120 20],... 'backg',get(S.fh,'color'),... 'fontsize',14,'fontweight','bold' ); set(S.fh,'windowbuttonmotionfcn',{@fh_wbmfcn,S}) % Set the motion detector. function [] = fh_wbmfcn(varargin) % WindowButtonMotionFcn for the figure. S = varargin{3}; % Get the structure. F = get(S.fh,'currentpoint'); % The current point w.r.t the figure. % Figure out of the current point is over the axes or not -> logicals. tf1 = S.AXP(1) <= F(1) && F(1) <= S.AXP(1) + S.AXP(3); tf2 = S.AXP(2) <= F(2) && F(2) <= S.AXP(2) + S.AXP(4); if tf1 && tf2 % Calculate the current point w.r.t. the axes. Cx = S.XLM(1) + (F(1)-S.AXP(1)).*(S.DFX/S.AXP(3)); Cy = S.YLM(1) + (F(2)-S.AXP(2)).*(S.DFY/S.AXP(4)); set(S.tx(2),'str',num2str([Cx,Cy],2)) end
github
jacksky64/imageProcessing-master
GUI_4.m
.m
imageProcessing-master/Matlab UI Examples/GUI_4.m
2,123
utf_8
32582b41a4cd6667c86782f8ff1bd51d
function [] = GUI_4() % Demonstrate how to make a multiline editbox. % Produces a GUI with an editbox on the left and a listbox on the right. % The user is invited to enter text into the editbox, either hitting return % at the end of each line or letting it wrap automatically. When the % button is pushed, each line of text from the editbox is placed as an % entry into the listbox. Notice the difference between how a wrapped line % is treated and a returned line is treated in the lisbox. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[450 450 400 200],... 'menubar','none',... 'name','Verify Password.',... 'resize','off',... 'numbertitle','off',... 'name','GUI_4'); S.ed = uicontrol('style','edit',... 'units','pix',... 'position',[10 60 190 120],... 'min',0,'max',2,... % This is the key to multiline edits. 'string',{'Enter text here'; 'then push the button.'},... 'fontweight','bold',... 'horizontalalign','center',... 'fontsize',11); S.ls = uicontrol('style','list',... 'units','pix',... 'position',[210 60 180 120],... 'backgroundcolor','w',... 'HorizontalAlign','left'); S.pb = uicontrol('style','push',... 'units','pix',... 'position',[10 10 380 40],... 'HorizontalAlign','left',... 'string','Transfer',... 'fontsize',14,'fontweight','bold',... 'callback',{@pb_call,S}); uicontrol(S.ed) % Give the editbox control. function [] = pb_call(varargin) % Callback for edit. S = varargin{3}; % Get the string from the edit box. Note that since the editbox is a % multiline editbox (max-min>2), the string returned is a cell array. E = get(S.ed,'string'); set(S.ls,'string',E) % Now set the listbox string to the value in E.
github
jacksky64/imageProcessing-master
GUI_12.m
.m
imageProcessing-master/Matlab UI Examples/GUI_12.m
1,271
utf_8
5740de8d4611642251d43dd181967882
function [] = GUI_12() % Demonstrate how to control the mouse pointer from a GUI. % Just for fun, show how to manipulate the mouse pointer. To close the % figure, use the regular window x in the upper right corner. % Note, I have had reports that nothing happens when this is run on Mac % computers. % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 300 160],... 'menubar','none',... 'name','GUI_12',... 'numbertitle','off',... 'resize','off'); S.UN = get(0,'units'); % We need to temporarily change this. S.pb = uicontrol('style','push',... 'units','pix',... 'position',[20 30 260 100],... 'string', 'Push Me To Close Figure',... 'fontsize',12,'fontweight','bold',... 'callback',{@pb_call,S}); set(S.fh,'WindowButtonMotionFcn',{@fh_wbmf,S}) function [] = fh_wbmf(varargin) S = varargin{3}; % Get the structure. set(0,'units','normalized') % Temporary, see below. % Move the mouse pointer to a random position. set(0, 'PointerLocation', [rand rand]) set(0,'units',S.UN) % Undo change to user's system. Good courtesy.
github
jacksky64/imageProcessing-master
GUI_7.m
.m
imageProcessing-master/Matlab UI Examples/GUI_7.m
1,564
utf_8
69bec55c368307c5844df39b23ef47c6
function [] = GUI_7() % Demonstrate how to store choice counters for multiple user choices. % Creates a popup with two choices and a textbox to display the number of % times each choice has been made. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 300 100],... 'menubar','none',... 'name','GUI_7',... 'numbertitle','off',... 'resize','off'); S.tx = uicontrol('style','tex',... 'unit','pix',... 'position',[10 15 280 20],... 'backgroundcolor',get(S.fh,'color'),... 'fontsize',12,'fontweight','bold',... 'string','OPTION 1: 0 OPTION 2: 0'); S.pp = uicontrol('style','pop',... 'unit','pix',... 'position',[10 60 280 20],... 'backgroundc',get(S.fh,'color'),... 'fontsize',12,'fontweight','bold',... 'string',{'option 1';'option 2'},'value',1); S.CNT = [0 0]; % Holds the number of times each option has been called. set(S.pp,'callback',{@pp_call,S}); % Set the callback. function [] = pp_call(varargin) % Callback for popupmenu. S = varargin{3}; % Get the structure. P = get(S.pp,'val'); % Get the users choice from the popup. S.CNT(P) = S.CNT(P) + 1; % Increment the counter. set(S.tx, 'string', sprintf('OPTION 1: %i OPTION 2: %i', S.CNT)); set(S.pp,'callback',{@pp_call,S}); % Save the new count.
github
jacksky64/imageProcessing-master
GUI_21.m
.m
imageProcessing-master/Matlab UI Examples/GUI_21.m
1,728
utf_8
21393eee213bf28e8eb3a5dfa563efe7
function [] = GUI_21() % Demonstrate how to get selection from a popup to an edit box & vis versa. % This is an expansion of GUI_20. Here we will enforce a specific list of % choices so that any text the user enters into the editbox which is not a % choice in the popup will be overwritten. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 300 110],... 'menubar','none',... 'name','GUI_21',... 'numbertitle','off',... 'resize','off'); S.pop = uicontrol('style','pop',... 'units','pixels',... 'position',[20 10 260 40],... 'string',{'one','two','three','four'}); S.ed = uicontrol('style','edit',... 'units','pix',... 'position',[20 60 260 30],... 'fontsize',16,... 'string','one'); set([S.pop,S.ed],{'callback'},{{@pop_call,S};{@ed_call,S}}); % Set callback function [] = pop_call(varargin) % Callback for the popup. S = varargin{3}; % Get the structure. P = get(S.pop,{'string','val'}); % Get the users choice. set(S.ed,'string',P{1}{P{2}}); % Assign the user's choice to the edit. function [] = ed_call(varargin) % Callback for the edit. S = varargin{3}; % Get the structure. E = get(S.ed,'string'); % Get the string from the edit. P = get(S.pop,{'string','value'}); % Get the users choice. % Check if edit string is found in pop-up list. tmp = strmatch(E,P{1}); if ~isempty(tmp) set(S.pop,'value',tmp) % Set the pop-up to match the edit. else set(S.ed,'string',P{1}{P{2}}) % Set the edit to current pop-up. end
github
jacksky64/imageProcessing-master
GUI_26.m
.m
imageProcessing-master/Matlab UI Examples/GUI_26.m
3,675
utf_8
be33aa9ec8e75f57511c587d1df4f065
function [] = GUI_26() % Demonstrate how to make the choices in several popups mutually exclusive. % Here we want three popups, with which the user can make three different % choices from the same set of choices. We want the users choices to be % made in any order. Once a certain value has been chosen through a popup, % that value should disappear from the lists for the other popups. The % user is allowed to change past choices, and popup lists will reflect % this. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('unit','pix',... 'position',[400 400 300 120],... 'menub','no',... 'name','GUI_26',... 'numbertitle','off',... 'resize','off'); S.STR = {'alfa ';'beta';'gamma';'delta';'omega'}; % String for popups. S.pp(1) = uicontrol('style','pop',... 'unit','pix',... 'position',[20 70 70 30],... 'string',S.STR); S.pp(2) = uicontrol('style','pop',... 'unit','pix',... 'position',[110 70 70 30],... 'string',S.STR,... 'value',2); S.pp(3) = uicontrol('style','pop',... 'unit','pix',... 'position',[210 70 70 30],... 'string',S.STR,... 'value',3); S.pb = uicontrol('style','push',... 'unit','pix',... 'posit',[20 20 260 30],... 'string','Print Choices',... 'callback',{@pb_call,S}); S.CHC = [0 0 0]; % To keep track of when a choice has been made. set(S.pp(:),'call',{@pp_call,S}); % All popups have the same callback. function [] = pb_call(varargin) % Callback for pushbutton, prints out the users choices. S = varargin{3}; % Get the structure. CHC = get(S.pp(:),{'string','value'}); fprintf('\n\t%s','Your choices are: '); for ii = 1:3 fprintf(' %s,',deblank(CHC{ii,1}{CHC{ii,2}})) end fprintf('\b\n\n') function [] = pp_call(varargin) % Callback for popups. [h,S] = varargin{[1,3]}; % Handle to cbo and structure. N = ~ismember(S.pp,h); % The other 2 popup menus. tmp = 1:3; % Instead of calling find twice, or setdiff, see next 2 lines. idx = tmp(~N); % The index to the current popup menu. idxo = tmp(N); % The indices into the other pops S.CHC(idx) = 1; % Let the subsequent calls know this choice has been made. CHC = get(h,{'string','value'}); % String and value of h. CHC = CHC{1}{CHC{2}}; ho = S.pp(N); % Handles to the other two popups. I = [1,2]; % Used in loop below. for ii = I s = get(ho(ii),{'string','value'}); % Get the iith other pop str,val. s = s{1}{s{2}}; % The current string for the iith pop. tmp = I(I~=ii); % Used to see if the other pop has made its choice. Str = S.STR; % Get the master string. Str(strmatch(CHC,Str)) = []; % Set this choice to null in master string. nm = get(ho(tmp),{'string','value'}); % Get the other pop's info. if S.CHC(idxo(tmp)) % The other-other pop has made a choice. Str(strmatch(nm{1}{nm{2}},Str)) = []; % Set this choice to null. end if strcmp(s,CHC) % The iith pop had same as new h, move it. for jj = 1:length(Str) if ~strcmp(Str{jj},CHC)&&~strcmp(Str{jj},nm{1}{nm{2}}) nm = strmatch(Str{jj},Str); break end end else nm = strmatch(s,Str); % Get the value for the iith pop. end set(ho(ii),'string',Str,'value',nm,'callb',{@pp_call,S}) % Assignments. end
github
jacksky64/imageProcessing-master
GUI_31.m
.m
imageProcessing-master/Matlab UI Examples/GUI_31.m
3,576
utf_8
93ebb5ecf307eb46c48da9107cfa2c37
function [] = GUI_31() % Demonstrate multiple uicontrol manipulations based on user choices. % Creates a simple calculator which allows the user to make a choice of % operations to use, as well as to enter numbers on which to operate. % Notice that the static textbox will update to show which operation is % current. % % Suggested exercise: Add more operations to the popup, and have the code % detect a rational answer (as best as you can with floating point, there % are many ways to do this, just pick some criteria). If the answer is % not rational, change the '=' to '~' to mean, 'approximately equal to.' % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[400 400 300 130],... 'menubar','none',... 'name','GUI_31',... 'numbertitle','off',... 'resize','off'); COL = get(S.fh,'color'); S.pp = uicontrol('style','pop',... 'unit','pix',... 'position',[10 20 120 30],... 'string',{'Add';'Multiply';'Subtract';'Divide';'Power'}); S.ed(1) = uicontrol('style','edit',... 'unit','pix',... 'position',[10 90 70 30],... 'string','3'); S.tx(1) = uicontrol('style','text',... 'unit','pix',... 'position',[85 90 20 30],... 'string','+',... 'fontsize',16,... 'backgroundcolor',COL); S.ed(2) = uicontrol('style','edit',... 'unit','pix',... 'position',[110 90 70 30],... 'string','2'); S.tx(2) = uicontrol('style','text',... 'unit','pix',... 'position',[185 90 20 30],... 'string','=',... 'fontsize',16,... 'backgroundcolor',COL); S.ed(3) = uicontrol('style','edit',... 'unit','pix',... 'position',[220 90 70 30],... 'string','answer'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[160 20 120 30],... 'string','Calculate',... 'call',{@pb_call,S}); set(S.pp,'callback',{@pp_call,S}); function [] = pb_call(varargin) % Callback for pushbutton S = varargin{3}; % Get the structure. N = str2double(get(S.ed(1:2),'string')); % The numbers to operate on. VL = get(S.pp,{'str','value'}); % Users choice from popup. switch VL{1}{VL{2}} % Users string choice from popup. case 'Add' N = num2str(sum(N)); case 'Multiply' N = num2str(prod(N)); case 'Subtract' N = num2str(-diff(N)); case 'Divide' N = num2str(N(1)/N(2)); case 'Power' N = num2str(N(1).^N(2)); otherwise end set(S.ed(3),'str',N) ; % Set the 'answer' editbox to display result. function [] = pp_call(varargin) % Callback for pushbutton S = varargin{3}; % Get the structure. VL = get(S.pp,{'str','value'}); % Users choice from popup. switch VL{1}{VL{2}} case 'Add' str = '+'; case 'Multiply' str = 'x'; case 'Subtract' str = '-'; case 'Divide' str = '/'; case 'Power' str = '^'; otherwise end set(S.tx(1),'string',str) % Change the textbox to display operation symb.
github
jacksky64/imageProcessing-master
GUI_13.m
.m
imageProcessing-master/Matlab UI Examples/GUI_13.m
1,730
utf_8
ebc363d98dd0c27fd9c73aadd9e13bb2
function [] = GUI_13() % Demonstrate how to display & change a slider's position with an edit box. % Slide the slider and it's position will be shown in the editbox. % Enter a valid number in the editbox and the slider will be moved to that % position. If the number entered is outside the range of the slider, % the number will be reset. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 300 100],... 'menubar','none',... 'name','GUI_13',... 'numbertitle','off',... 'resize','off'); S.sl = uicontrol('style','slide',... 'unit','pix',... 'position',[20 10 260 30],... 'min',1,'max',100,'val',50); S.ed = uicontrol('style','edit',... 'unit','pix',... 'position',[20 50 260 30],... 'fontsize',16,... 'string','50'); set([S.ed,S.sl],'call',{@ed_call,S}); % Shared Callback. function [] = ed_call(varargin) % Callback for the edit box and slider. [h,S] = varargin{[1,3]}; % Get calling handle and structure. switch h % Who called? case S.ed L = get(S.sl,{'min','max','value'}); % Get the slider's info. E = str2double(get(h,'string')); % Numerical edit string. if E >= L{1} && E <= L{2} set(S.sl,'value',E) % E falls within range of slider. else set(h,'string',L{3}) % User tried to set slider out of range. end case S.sl set(S.ed,'string',get(h,'value')) % Set edit to current slider. otherwise % Do nothing, or whatever. end
github
jacksky64/imageProcessing-master
GUI_32.m
.m
imageProcessing-master/Matlab UI Examples/GUI_32.m
4,357
utf_8
42de6df214b8d88a186603d8aaef6257
function [] = GUI_32(str) % Demonstrate how to get data from a GUI into the base workspace without % "poofing" unawares. This is based on GUI_31. When called with a string % argument, all of the operations performed by the user will be recorded % and returned to the base workspace in a variable of the name given by the % string. This happens when the GUI is closed. If no string argument is % used, the data is not created in the base workspace. % % Example: % % GUI_32('Myops') % Call this then perform a few operations. % % After closing the GUI, call: % Myops % at the command line displays a record of operations. % % Suggested exercise: Alter the code so that the variable in the base % workspace is created upon GUI initialization. Then update the data after % every new operation. % % % Author: Matt Fig % Date: 7/15/2009 if nargin==0 str = []; % User called the GUI without and output name. elseif ~ischar(str) error('Only a string argument is valid. See help.') elseif ~isvarname(str) % User passed something like: 0.?6# error('String must be a valid variable name. See help.') end S.STR = str; % The name of the variable the user wishes to have in base. S.CNT = 0; % The number of times user pressed the pushbutton. S.CHC = []; % Holds the strings which represent the operations performed. S.fh = figure('units','pixels',... 'position',[400 400 300 130],... 'menubar','none',... 'name','GUI_32',... 'numbertitle','off',... 'resize','off',... 'deletefcn',{@fig_del,S}); COL = get(S.fh,'color'); S.pp = uicontrol('style','pop',... 'unit','pix',... 'position',[10 20 120 30],... 'string',{'Add';'Multiply';'Subtract';'Divide';'Power'}); S.ed(1) = uicontrol('style','edit',... 'unit','pix',... 'position',[10 90 70 30],... 'string','3'); S.tx(1) = uicontrol('style','text',... 'unit','pix',... 'position',[85 90 20 30],... 'string','+',... 'fontsize',16,... 'backgroundcolor',COL); S.ed(2) = uicontrol('style','edit',... 'unit','pix',... 'position',[110 90 70 30],... 'string','2'); S.tx(2) = uicontrol('style','text',... 'unit','pix',... 'position',[185 90 20 30],... 'string','=',... 'fontsize',16,... 'backgroundcolor',COL); S.ed(3) = uicontrol('style','edit',... 'unit','pix',... 'position',[220 90 70 30],... 'string','answer'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[160 20 120 30],... 'string','Calculate'); set([S.pp,S.pb],'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for pushbutton S = varargin{3}; % Get the structure. N = str2double(get(S.ed(1:2),'string')); % Numbers from edits to op. on. VL = get(S.pp,{'str','value'}); % User's choice from popup. % Now get the string updates and perform operations. switch VL{1}{VL{2}} % User's string choice. case 'Add' A = sum(N); str = '+'; case 'Multiply' A = prod(N); str = 'x'; case 'Subtract' A = -diff(N); str = '-'; case 'Divide' A = N(1)/N(2); str = '/'; case 'Power' A = N(1).^N(2); str = '^'; otherwise end set(S.tx(1),'string',str) % Set the operation display. if varargin{1}==S.pb % This stuff we only need to do if button is pushed. S.CNT = S.CNT + 1; set(S.ed(3),'str',A) S.CHC{S.CNT,1} = sprintf('%2.2f %s %2.2f %s %2.2f',N(1),str,N(2),'=',A); set(S.pb,'callback',{@pb_call,S}) set(S.fh,'deletefcn',{@fig_del,S}) end function [] = fig_del(varargin) S = varargin{3}; if ~isempty(S.STR) assignin('base',S.STR,S.CHC) % Assign the data to the base workspace. end
github
jacksky64/imageProcessing-master
GUI_33.m
.m
imageProcessing-master/Matlab UI Examples/GUI_33.m
4,321
utf_8
e186426586a4268ad76582e4859822c6
function [] = GUI_33() % Demonstrate how to export data with context menu. % Demonstrate how to get data from a GUI into the base workspace without % "poofing" unawares. This is based on GUI_31. When user is ready to % retrieve the data, simply right-click anywhere inside the figure to get % to the context menu. User will be prompted to enter a variable name to % which will be assigned the data in the base workspace. % % % Author: Matt Fig % Date: 7/15/2009 S.CNT = 0; % The number of times user pressed the pushbutton. S.CHC = []; % Holds the strings which represent the operations performed. S.fh = figure('units','pixels',... 'position',[400 400 300 130],... 'menubar','none',... 'name','GUI_33',... 'numbertitle','off',... 'resize','off'); COL = get(S.fh,'color'); S.pp = uicontrol('style','pop',... 'unit','pix',... 'position',[10 20 120 30],... 'string',{'Add';'Multiply';'Subtract';'Divide';'Power'}); S.ed(1) = uicontrol('style','edit',... 'unit','pix',... 'position',[10 90 70 30],... 'string','3'); S.tx(1) = uicontrol('style','text',... 'unit','pix',... 'position',[85 90 20 30],... 'string','+',... 'fontsize',16,... 'backgroundcolor',COL); S.ed(2) = uicontrol('style','edit',... 'unit','pix',... 'position',[110 90 70 30],... 'string','2'); S.tx(2) = uicontrol('style','text',... 'unit','pix',... 'position',[185 90 20 30],... 'string','=',... 'fontsize',16,... 'backgroundcolor',COL); S.ed(3) = uicontrol('style','edit',... 'unit','pix',... 'position',[220 90 70 30],... 'string','answer'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[160 20 120 30],... 'string','Calculate'); S.cm = uicontextmenu; S.um = uimenu(S.cm,... 'label','Export Data to Base',... 'Callback', {@um_call,S}); set([S.fh,S.pp,S.ed,S.tx,S.pb],'uicontextmenu',S.cm); % Assign contextmen. set([S.pp,S.pb],'callback',{@pb_call,S}); % Assign callbacks. function [] = pb_call(varargin) % Callback for pushbutton S = varargin{3}; % Get the structure. N = str2double(get(S.ed(1:2),'string')); % The numbers to operate on. VL = get(S.pp,{'str','value'}); % User's choice of operation. % Now get the string updates and perform operations. switch VL{1}{VL{2}} % User's string choice from popup. case 'Add' A = sum(N); str = '+'; case 'Multiply' A = prod(N); str = 'x'; case 'Subtract' A = -diff(N); str = '-'; case 'Divide' A = N(1)/N(2); str = '/'; case 'Power' A = N(1).^N(2); str = '^'; otherwise end set(S.tx(1),'string',str) % Set the operation display. if varargin{1}==S.pb % This stuff we only need to do if button is pushed. S.CNT = S.CNT + 1; set(S.ed(3),'str',A) S.CHC{S.CNT,1} = sprintf('%2.2f %s %2.2f %s %2.2f',N(1),str,N(2),'=',A); set(S.pb,'callback',{@pb_call,S}) set(S.um,'Callback', {@um_call,S}); end function [] = um_call(varargin) S = varargin{3}; % Get the structure. % Create our input dialog box args. prompt = 'Name of the variable to create?'; name = 'Enter a variable name.'; numlines = 1; defaultanswer = {'MyData'}; var = '5t;-'; % An invalid variable name. % Note that there should be an error check in here in case the user entered % an invalid variable name. while ~isvarname(var) var = inputdlg(prompt,name,numlines,defaultanswer); var = var{1}; end assignin('base',var,S.CHC) % Assign the data to the base workspace. % If one wanted, a msgbox could be added here to let the user know that the % data is now available in the base workspace.
github
jacksky64/imageProcessing-master
GUI_22.m
.m
imageProcessing-master/Matlab UI Examples/GUI_22.m
1,928
utf_8
a5cb0a1c676409bd72fe711b9e4169cb
function [] = GUI_22() % Demonstrate how to get selection from a popup to an edit box & vis versa. % This is an expansion of GUI_20. Here we will not enforce a specific list % of choices so that any text the user enters into the editbox will be % added to the popup list if it is not already there. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 300 110],... 'menubar','none',... 'name','GUI_22',... 'numbertitle','off',... 'resize','off'); S.pop = uicontrol('style','pop',... 'units','pixels',... 'position',[20 10 260 40],... 'string',{'one','two','three','four'}); S.ed = uicontrol('style','edit',... 'units','pix',... 'position',[20 60 260 30],... 'fontsize',16,'string','one'); set([S.pop,S.ed],{'callback'},{{@pp_call,S};{@ed_call,S}}); function [] = pp_call(varargin) % Callback for the popup. S = varargin{3}; % Get the structure. P = get(S.pop,{'string','val'}); % Get the users choice. set(S.ed,'string',P{1}{P{2}}); % Assign the user's choice to the edit. function [] = ed_call(varargin) % Callback for the edit. S = varargin{3}; % Get the structure. E = get(S.ed,'string'); % Get the string from the edit. P = get(S.pop,{'string','value'}); % Get the users choice. % Check if edit string is found in pop-up list. tmp = strmatch(E,P{1}); if ~isempty(tmp) set(S.pop,'value',tmp) % Set the pop-up to match the edit. else % We could add the new element to the popup string at either the top or % the bottom. Both methods are shown below. Only uncomment one of % these at a time! set(S.pop,'string',{P{1}{:},E},'value',length(P{1})+1) % Bottom % set(S.pop,'string',{E,P{1}{:}},'value',1) % Top end
github
jacksky64/imageProcessing-master
GUI_3.m
.m
imageProcessing-master/Matlab UI Examples/GUI_3.m
1,541
utf_8
d3fd0091e8f1cf8142980cd48db68289
function [] = GUI_3() % Demonstrate how to hide a uicontrol from the user. % Creates a textbox and a checkbox. The state of the checkbox determines % whether or not the textbox is visible. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 200 130],... 'menubar','none',... 'name','GUI_3',... 'numbertitle','off',... 'resize','off'); S.tx = uicontrol('style','text',... 'unit','pix',... 'position',[10 70 180 40],... 'string','Hello',... 'backgroundcolor','r',... 'fontsize',23); S.ch = uicontrol('style','check',... 'unit','pix',... 'position',[10 20 180 35],... 'string',' Check2hide',... 'fontsize',14); set(S.ch,'callback',{@ch_call,S}) % Set callback. function [] = ch_call(varargin) % Callback for pushbutton. S = varargin{3}; % Get the structure. switch get(S.tx,'visible') case 'on' % The text is visible, make it invisible. set(S.ch,'string',' Uncheck2show'); set(S.tx,'visible','off') case 'off' % The text is invisible, make it visible. set(S.ch,'string',' Check2hide'); set(S.tx,'visible','on') otherwise % This should never happen! disp('Matlab entered the twilight zone, aborting.') close(S.fh) quit end
github
jacksky64/imageProcessing-master
GUI_25.m
.m
imageProcessing-master/Matlab UI Examples/GUI_25.m
3,018
utf_8
1b008e30b7eb2b222dd92dc3b2e5c22f
function [] = GUI_25() % Demonstrate how to make an image loader. % Creates a GUI which looks for files with the extention .jpg in the % current directory. A listbox is populated with the names of all such % files, and is empty if none exist in the current directory. When the % pushbutton is activated, the current selection in the listbox is read % into a variable in the base workspace. The name of the variable will % have a timestamp so as to minimize the chances of overwriting another % variable. For example, say the selected image file is called Mypic.jpg % The base workspace variable will be Mypic_10_05_21 if the pushbutton was % pushed as 10:05:21 according to the system clock. % % Suggested exercise: Modify the code so that the user could pass in % the extention of the image file-type which they wished to load. In the % callback section, there should be some kind of check for indexed % images, and appropriate action taken. Further: modify this file so that % the user can pass in a directory name within which to search, or add a % browse button to the GUI. % % % % Author: Matt Fig % Date: 7/15/2009 D = dir('*.jpg'); % or jpeg or whatever. S.NAM = {D(:).name}; % Store the name of all items returned in D. S.fh = figure('units','pixels',... 'position',[450 450 400 200],... 'menubar','none',... 'name','Verify Password.',... 'resize','off',... 'numbertitle','off',... 'name','GUI_25'); S.ls = uicontrol('style','list',... 'units','pix',... 'position',[10 60 380 120],... 'backgroundcolor','w',... 'string',S.NAM,... 'HorizontalAlign','left'); S.pb = uicontrol('style','push',... 'units','pix',... 'position',[10 10 380 40],... 'backgroundcolor','w',... 'HorizontalAlign','left',... 'string','Load Image',... 'fontsize',14,'fontweight','bold',... 'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for pushbutton. S = varargin{3}; L = get(S.ls,{'string';'value'}); % Get the editbox string try L = L{1}{L{2}}; % Give it a name for the base workspace. X = imread(L); % Read the image. % Next we will append a timestamp to the variable name so that we % minimize the chances of overwriting a variable in the base % workspace. There are many other ways to handle this, so feel free to % experiment with alternatives. str = [L(1:end-4),'_',strrep(datestr(now,'HH:MM:SS'),':','_')]; assignin('base',str,X) % Create the variable in the base workspace. catch % Also more could be done here as far as returning what kind of error, % or offereing other suggestions to the user, etc. fprintf('\t\t%s\n','No file selected, or read error.') end
github
jacksky64/imageProcessing-master
image_compare_tool.m
.m
imageProcessing-master/imagecompare/image_compare_tool.m
1,897
utf_8
d5ce0339bf9a468a84b11ece78f99394
function image_compare_tool(left_image, right_image) % Create the figure hFig = figure('Toolbar','none',... 'Menubar','none',... 'Name','Image Compare Tool',... 'NumberTitle','off',... 'IntegerHandle','off'); % Display left image subplot(121) hImL = imshow(left_image); % Display right image subplot(122) hImR = imshow(right_image); % Create a scroll panel for left image hSpL = imscrollpanel(hFig,hImL); set(hSpL,'Units','normalized',... 'Position',[0 0.1 .5 0.9]) % Create scroll panel for right image hSpR = imscrollpanel(hFig,hImR); set(hSpR,'Units','normalized',... 'Position',[0.5 0.1 .5 0.9]) % Add a Magnification box hMagBox = immagbox(hFig,hImL); pos = get(hMagBox,'Position'); set(hMagBox,'Position',[0 0 pos(3) pos(4)]) % Add a pixel info hl = impixelinfo(hFig,hImL); set(hl,'Position',[20 20 200 pos(4)]) hr = impixelinfo(hFig,hImR); set(hr,'Position',[220 20 200 pos(4)]) %% Add an Overview tool imoverview(hImL) %% Get APIs from the scroll panels apiL = iptgetapi(hSpL); apiR = iptgetapi(hSpR); %% Synchronize left and right scroll panels apiL.setMagnification(apiR.getMagnification()) apiL.setVisibleLocation(apiR.getVisibleLocation()) % When magnification changes on left scroll panel, % tell right scroll panel apiL.addNewMagnificationCallback(apiR.setMagnification); % When magnification changes on right scroll panel, % tell left scroll panel apiR.addNewMagnificationCallback(apiL.setMagnification); % When location changes on left scroll panel, % tell right scroll panel apiL.addNewLocationCallback(apiR.setVisibleLocation); % When location changes on right scroll panel, % tell left scroll panel apiR.addNewLocationCallback(apiL.setVisibleLocation); hf1=imcontrast(hImL); hf2=imcontrast(hImR);
github
jacksky64/imageProcessing-master
GaborFilterDesighnNik.m
.m
imageProcessing-master/gaborFilterDesign/GaborFilterDesighnNik.m
34,966
utf_8
9f7447b4806b3da2d5248db380c94a09
function varargout = GaborFilterDesighnNik(varargin) %% %function varargout = GaborFilterDesighnNik(varargin) % % Functional purpose: I've made this GUI for a couple of students, which were learning the Gabor Filtering, and had hard % time to understand the sunbject. This helped them to get some intuition about what Gabor Filtering is, what are it's % benefits and what are it's uses. This GUI allowes you to play with Gabor filters in order to understand this important % topic. The user may define a Gabor Filter with all possible parameters, and to filter an image he wishes to. He then % can see the filtered image, in spatial and frewquncy domain, it's phase and amplitude (as it's unreal signal). The % filtered can beviewed in spatioal/frequncy domain, and it can be saved for future use. % % Input arguments: None. (Actually GUI settings defned by user). % % Output Arguments: None % % Issues & Comments: None % % Author and Date: Nikolay Skarbnik 7/07/2008. %% % GABORFILTERDESIGHNNIK M-file for GaborFilterDesighnNik.fig % GABORFILTERDESIGHNNIK, by itself, creates a new GABORFILTERDESIGHNNIK or raises the existing % singleton*. % % H = GABORFILTERDESIGHNNIK returns the handle to a new GABORFILTERDESIGHNNIK or the handle to % the existing singleton*. % % GABORFILTERDESIGHNNIK('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in GABORFILTERDESIGHNNIK.M with the given input arguments. % % GABORFILTERDESIGHNNIK('Property','Value',...) creates a new GABORFILTERDESIGHNNIK or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before GaborFilterDesighnNik_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to GaborFilterDesighnNik_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 GaborFilterDesighnNik % Last Modified by GUIDE v2.5 15-Mar-2011 23:05:01 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @GaborFilterDesighnNik_OpeningFcn, ... 'gui_OutputFcn', @GaborFilterDesighnNik_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 GaborFilterDesighnNik is made visible. function GaborFilterDesighnNik_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 GaborFilterDesighnNik (see VARARGIN) % Choose default command line output for GaborFilterDesighnNik handles.output = hObject; % Update handles structure guidata(hObject, handles); % This sets up the initial plot - only do when we are invisible % so window can get raised using GaborFilterDesighnNik. if strcmp(get(hObject,'Visible'),'off') imagesc(peaks(200)); text(100,20,'Gabor filter visual GUI','FontSize',28,'FontName','Castellar','HorizontalAlignment','center','FontWeight','Bold'); Str_array={' Dear user, please do the following:','1) Define the filter, by changing the Mother Gabor parameters',... ' or, by loading a previoly saved filter',' (you can view your filter in both time and frequency domains)',... '2) Load an image','3) Finally, apply the filter','4) Using the "Show" and "Filtered Image" ',... ' button combination you can see the resulting image... '}; text(10,80,Str_array,'FontSize',20,'FontName','Kartika'); text(20,180,'\copyright Nikolay S.','FontSize',14,'HorizontalAlignment','center'); end % UIWAIT makes GaborFilterDesighnNik wait for user response (see UIRESUME) % uiwait(handles.GaborFiltGUINik); % --- Outputs from this function are returned to the command line. function varargout = GaborFilterDesighnNik_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % -------------------------------------------------------------------- function FileMenu_Callback(hObject, eventdata, handles) % hObject handle to FileMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function OpenMenuItem_Callback(hObject, eventdata, handles) % hObject handle to OpenMenuItem (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) file = uigetfile('*.fig'); if ~isequal(file, 0) open(file); end % -------------------------------------------------------------------- function PrintMenuItem_Callback(hObject, eventdata, handles) % hObject handle to PrintMenuItem (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) printdlg(handles.GaborFiltGUINik) % -------------------------------------------------------------------- function CloseMenuItem_Callback(hObject, eventdata, handles) % hObject handle to CloseMenuItem (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) selection = questdlg(['Close ' get(handles.GaborFiltGUINik,'Name') '?'],... ['Close ' get(handles.GaborFiltGUINik,'Name') '...'],... 'Yes','No','Yes'); if strcmp(selection,'No') return; end delete(handles.GaborFiltGUINik) % --- Executes on selection change in Graph_type_popup. function Graph_type_popup_Callback(hObject, eventdata, handles) % hObject handle to Graph_type_popup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns Graph_type_popup contents as cell array % contents{get(hObject,'Value')} returns selected item from Graph_type_popup n=get(handles.N_edit,'Value') ; x=linspace(get(handles.X_min_edit,'Value'),get(handles.X_max_edit,'Value'),n); y=linspace(get(handles.Y_min_edit,'Value'),get(handles.Y_max_edit,'Value'),n); G=real(handles.FilterData); %real(get(hObject,'UserData')); if (get(handles.Frequency_radiobutton,'Value')) G=abs(fftshift(fft2(G))); end if (get(handles.Hold_on_checkbox,'Value')) hold on; else hold off; end switch (get(handles.Graph_type_popup,'Value')) case (1) imagesc(x,y,G); case (2) mesh(x,y,G); case (3) surf(x,y,G); end % --- Executes during object creation, after setting all properties. function Graph_type_popup_CreateFcn(hObject, eventdata, handles) % hObject handle to Graph_type_popup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end set(hObject, 'String', {'imagesc', 'mesh', 'surf'}); function N_edit_Callback(hObject, eventdata, handles) % hObject handle to N_edit (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 N_edit as text % str2double(get(hObject,'String')) returns contents of N_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function N_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to N_edit (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_min_edit_Callback(hObject, eventdata, handles) % hObject handle to X_min_edit (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_min_edit as text % str2double(get(hObject,'String')) returns contents of X_min_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function X_min_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to X_min_edit (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_max_edit_Callback(hObject, eventdata, handles) % hObject handle to X_max_edit (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_max_edit as text % str2double(get(hObject,'String')) returns contents of X_max_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function X_max_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to X_max_edit (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_min_edit_Callback(hObject, eventdata, handles) % hObject handle to Y_min_edit (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_min_edit as text % str2double(get(hObject,'String')) returns contents of Y_min_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function Y_min_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to Y_min_edit (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_max_edit_Callback(hObject, eventdata, handles) % hObject handle to Y_max_edit (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_max_edit as text % str2double(get(hObject,'String')) returns contents of Y_max_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function Y_max_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to Y_max_edit (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 Frequency_edit_Callback(hObject, eventdata, handles) % hObject handle to Frequency_edit (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 Frequency_edit as text % str2double(get(hObject,'String')) returns contents of Frequency_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function Frequency_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to Frequency_edit (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 Rotation_Angle_edit_Callback(hObject, eventdata, handles) % hObject handle to Rotation_Angle_edit (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 Rotation_Angle_edit as text % str2double(get(hObject,'String')) returns contents of Rotation_Angle_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function Rotation_Angle_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to Rotation_Angle_edit (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 Sigma_x_edit_Callback(hObject, eventdata, handles) % hObject handle to Sigma_x_edit (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 Sigma_x_edit as text % str2double(get(hObject,'String')) returns contents of Sigma_x_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function Sigma_x_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to Sigma_x_edit (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 Sigma_y_edit_Callback(hObject, eventdata, handles) % hObject handle to Sigma_y_edit (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 Sigma_y_edit as text % str2double(get(hObject,'String')) returns contents of Sigma_y_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function Sigma_y_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to Sigma_y_edit (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 during object creation, after setting all properties. function axes1_CreateFcn(hObject, eventdata, handles) % hObject handle to axes1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: place code in OpeningFcn to populate axes1 set(hObject,'FontSize',1e-3); function Phase_shift_edit_Callback(hObject, eventdata, handles) % hObject handle to Phase_shift_edit (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 Phase_shift_edit as text % str2double(get(hObject,'String')) returns contents of Phase_shift_edit as a double parameter_changed(hObject) % --- Executes during object creation, after setting all properties. function Phase_shift_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to Phase_shift_edit (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 Time_radiobutton. function Time_radiobutton_Callback(hObject, eventdata, handles) % hObject handle to Time_radiobutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Time_radiobutton eventdata='datachanged'; Graph_type_popup_Callback(handles.Graph_type_popup, eventdata, handles) % --- Executes on button press in Frequency_radiobutton. function Frequency_radiobutton_Callback(hObject, eventdata, handles) % hObject handle to Frequency_radiobutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Frequency_radiobutton eventdata='datachanged'; Graph_type_popup_Callback(handles.Graph_type_popup, eventdata, handles) function parameter_changed(hObject) set(hObject,'Value',str2double(get(hObject,'String'))); % "edit" object value, is the numeric value of the string. handles=guidata(hObject); n=get(handles.N_edit,'Value') ; Sigma_x=get(handles.Sigma_x_edit,'Value') ; Sigma_y=get(handles.Sigma_y_edit,'Value') ; x=linspace(get(handles.X_min_edit,'Value'),get(handles.X_max_edit,'Value'),n); y=linspace(get(handles.Y_min_edit,'Value'),get(handles.Y_max_edit,'Value'),n); % set(handles.axes1,'XLim',[x(1), x(end)]); % set(handles.axes1,'YLim',[y(1), y(end)]); axis([x(1), x(end), y(1), y(end)]); F=get(handles.Frequency_edit,'Value') ; % modulation freq Theta= get(handles.Rotation_Angle_edit,'Value')*pi/180; Phase_shift=get(handles.Phase_shift_edit,'Value'); % [x_rot,y_rot]=my_rotate(x,y,Theta); [X,Y]=meshgrid(x,y); X_rot=X*cos(Theta)+Y*sin(Theta); Y_rot=-X*sin(Theta)+Y*cos(Theta); GaussianMat=1/(2*pi*Sigma_x*Sigma_y)*exp((-((X_rot)/Sigma_x).^2-((Y_rot)/Sigma_y).^2)/2);%exp((-(X_rot)/(Sigma_x)^2-(Y_rot)/(Sigma_y)^2)/2); % GaussianMat=myGaussian(x_rot, Sigma_x)'*myGaussian(y_rot, Sigma_y); % FreqModulation=zeros(size(GaussianMat)); % % for n=1:length(y) % for m=1:length(x) % FreqModulation(n,m)=exp(j*F*2*pi*(x(m)*cos(Theta)+y(n)*sin(Theta))); % end % end FreqModulation=exp(j*(F*2*pi*X_rot+Phase_shift)); % FreqModulation=exp(2*pi*i*F*repmat(x_rot,length(y_rot),1));%'*ones(size(x_rot)); % FreqModulation=exp(2*pi*i*F*x_rot)'*exp(2*pi*i*F*y_rot+Phase_shift); %repmat(exp(2*i*pi*F*x),m,1); GaborFilter=GaussianMat.*FreqModulation; handles.FilterData=GaborFilter; % Save the resulting Gabor filter %set(handles.Graph_type_popup,'UserData',GaborFilter); guidata(hObject,handles); eventdata='datachanged'; Graph_type_popup_Callback(handles.Graph_type_popup, eventdata, handles) function G=myGaussian(x, sigma,mean) if nargin<3 mean=0; if nargin<2 sigma=1; end end G=1/(2*pi)*exp(-((x-mean)/sigma).^2/2); function [x_rot,y_rot]=my_rotate(x,y,Theta) %function [x_rot,y_rot]=my_rotate(x,y,Theta) % Rotates X and Y by agle Theta (Theta is given in rad) x_rot=x*cos(Theta)+y*sin(Theta); y_rot=-x*sin(Theta)+y*cos(Theta); function error_accured(handles, error_String) % function error_accured(handles, error_String) % the function desplays an error string on the GUI screen, once an error % accures. set (handles.ErrorText,'String',error_String); set (handles.ErrorPanel,'Visible','On');%set ([handles.ErrorText, handles.ErrorOffButton],'Visible','On'); % --- Executes on button press in Hold_on_checkbox. function Hold_on_checkbox_Callback(hObject, eventdata, handles) % hObject handle to Hold_on_checkbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Hold_on_checkbox % --- Executes on button press in LoadButton. function LoadButton_Callback(hObject, eventdata, handles) % hObject handle to LoadButton (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); switch (get(handles.FileTypeMenu,'Value')) case(1) %('Image') FilterSpec={'*.jpg;*.jpeg;*.gif;*.bmp;*.png;*.tiff','Image Files (*.jpg;*.jpeg;*.gif;*.bmp;*.png;*.tiff)'}; DialogTitle='Select an Image file'; case(2) %('Filter') FilterSpec='*.mat'; DialogTitle='Select a previolsy saved Filter file'; case(3) %('Filtered Image') FilterSpec='*.mat'; DialogTitle='Select a previolsy saved Filtered Image file'; end [FileName,PathName,FilterIndex] = uigetfile(FilterSpec,DialogTitle); if isequal(FileName,0) error_accured(handles, 'No such file exists. Choose a file.') if strcmpi(get(handles.ApplyFilterButton,'Enable'),'On') set(handles.ApplyFilterButton,'Enable','Off'); end else set(handles.FilePathEdit,'String',PathName); set(handles.FileNameEdit,'String',FileName); if strcmpi(get(handles.ApplyFilterButton,'Enable'),'Off') set(handles.ApplyFilterButton,'Enable','On'); end end switch (get(handles.FileTypeMenu,'Value')) case(1) %('Image') ImageDataTmp=imread([PathName,FileName]); if (size(ImageDataTmp,3)==3) %work with Gray iamges only!!! ImageDataTmp=rgb2gray(ImageDataTmp); end handles.ImageData=double(ImageDataTmp); case(2) %('Filter') FilterDataTmp=load([PathName,FileName]); handles.FilterData=FilterDataTmp.tmp; case{3,4} %('Filtered Image') FilteredImageDataTmp=load([PathName,FileName]); handles.FilteredImageData=FilteredImageDataTmp.tmp; end guidata(hObject,handles); % --- Executes on button press in SaveButton. function SaveButton_Callback(hObject, eventdata, handles) % hObject handle to SaveButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) FileName=get(handles.FileNameEdit,'String'); PathName=get(handles.FilePathEdit,'String'); if isempty(strfind(FileName,'.mat')) % Error, trying to save .mat output in a non *.mat file!!! error_accured(handles, 'Attempt to save .mat output in a non *.mat file!!!') end tmp=[]; switch (get(handles.FileTypeMenu,'Value')) case(1) %('Image') %Do nothing here. Saving the image is obsolite at this point case(2) %('Filter') tmp=handles.FilterData; case{3,4} %('Filtered Image') tmp=handles.FilteredImageData; end if ~isempty(tmp) save([PathName,FileName],'tmp'); end; function FilePathEdit_Callback(hObject, eventdata, handles) % hObject handle to FilePathEdit (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 FilePathEdit as text % str2double(get(hObject,'String')) returns contents of FilePathEdit as a double % --- Executes during object creation, after setting all properties. function FilePathEdit_CreateFcn(hObject, eventdata, handles) % hObject handle to FilePathEdit (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 FileNameEdit_Callback(hObject, eventdata, handles) % hObject handle to FileNameEdit (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 FileNameEdit as text % str2double(get(hObject,'String')) returns contents of FileNameEdit as a double % --- Executes during object creation, after setting all properties. function FileNameEdit_CreateFcn(hObject, eventdata, handles) % hObject handle to FileNameEdit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in FileTypeMenu. function FileTypeMenu_Callback(hObject, eventdata, handles) % hObject handle to FileTypeMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns FileTypeMenu contents as cell array % contents{get(hObject,'Value')} returns selected item from FileTypeMenu % --- Executes during object creation, after setting all properties. function FileTypeMenu_CreateFcn(hObject, eventdata, handles) % hObject handle to FileTypeMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ShowButton. function ShowButton_Callback(hObject, eventdata, handles) % hObject handle to ShowButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if (get(handles.NewFigCheckBox,'Value')) figure; % if checkbox is on, plot graph in a new window % title(['Image of ', get(handles.FileTypeMenu,'String')]); % hold on; end switch (get(handles.FileTypeMenu,'Value')) case(1) %('Image') imshow(uint8(handles.ImageData)); % if (get(handles.Frequency_radiobutton,'Value')) % image(abs(fft2(handles.ImageData))); % else % imshow(uint8(handles.ImageData)); % end case(2) %('Filter') eventdata='Show Button was pressed'; Graph_type_popup_Callback(hObject, eventdata, handles) case(3) %('Filtered ImageAmplitude') if isempty(handles.FilteredImageData) eventdata='Filtered Image data is needed'; ApplyFilterButton_Callback(hObject, eventdata, handles); % guidata(hObject,handles); % handles=guidata(hObject); % update handle structure end % if (get(handles.Frequency_radiobutton,'Value')) % image(abs(fft2(handles.FilteredImageData))); % else % imshow(uint8(real(handles.FilteredImageData))); % Showing only real part of filtered image % end imshow(Scale2Uint(abs(handles.FilteredImageData))); % Showing only absolute value of the filtered image case(4) %('Filtered Image Phaze') if isempty(handles.FilteredImageData) eventdata='Filtered Image data is needed'; ApplyFilterButton_Callback(hObject, eventdata, handles); end % imshow(uint8(angle(handles.FilteredImageData))); % Showing only real part of filtered image scalled_amp=Scale2Uint(abs(handles.FilteredImageData)); scalled_phase=Scale2Uint(angle(handles.FilteredImageData)); % ind=scalled_amp==0; % scalled_phase(ind)=0;%set phase for low amplitudes to zero scalled_phase(scalled_amp<1)=0;%set phase for low amplitudes to zero imshow(scalled_phase); % Showing the angle value of the filtered image case(5) %('Laplasina(Filtered Image Phaze)') if isempty(handles.FilteredImageData) eventdata='Filtered Image data is needed'; ApplyFilterButton_Callback(hObject, eventdata, handles); end % imshow(uint8(angle(handles.FilteredImageData))); % Showing only real part of filtered image imshow(Scale2Uint(del2(angle(handles.FilteredImageData)))); % Showing the angle value of the filtered image case(6) %('Gaussian(Filtered Image Phaze)') if isempty(handles.FilteredImageData) eventdata='Filtered Image data is needed'; ApplyFilterButton_Callback(hObject, eventdata, handles); end % imshow(uint8(angle(handles.FilteredImageData))); % Showing only real part of filtered image imshow(Scale2Uint(gradient(angle(handles.FilteredImageData)))); % Showing the angle value of the filtered image end if (get(handles.NewFigCheckBox,'Value')) temp_str_arr=get(handles.FileTypeMenu,'String'); temp_str=temp_str_arr(get(handles.FileTypeMenu,'Value')); title(temp_str,'FontSize',18); end % --- Executes on button press in ApplyFilterButton. function ApplyFilterButton_Callback(hObject, eventdata, handles) % hObject handle to ApplyFilterButton (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); if isempty(handles.ImageData) error_accured(handles, 'No Image file loaded'); end set(handles.GaborFiltGUINik,'Pointer','watch'); drawnow; % uiwait(handles.GaborFiltGUINik); if size(handles.ImageData,3)==3 handles.FilteredImageData=[]; for i=1:3 handles.FilteredImageData(:,:,i)=filter2(handles.FilterData,handles.ImageData(:,:,i),'same'); end else handles.FilteredImageData=filter2(handles.FilterData,handles.ImageData,'same');%conv2(handles.FilterData,handles.ImageData); end set(handles.GaborFiltGUINik,'Pointer','arrow');drawnow; guidata(hObject,handles); % --- Executes during object creation, after setting all properties. function GaborFiltGUINik_CreateFcn(hObject, eventdata, handles) % hObject handle to GaborFiltGUINik (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called handles=guidata(hObject); home; % scrole screen up fprintf('\n\n %s \n\n','(NikolayS) Gabor Filter generation and application GUI started '); handles.ImageData=[]; % Init vriables, so isempty function can be applied to them. handles.FilterData=[]; handles.FilteredImageData=[]; guidata(hObject,handles); % --- Executes on button press in ErrorOffButton. function ErrorOffButton_Callback(hObject, eventdata, handles) % hObject handle to ErrorOffButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %set ([handles.ErrorText, handles.ErrorOffButton],'Visible','Off'); set (handles.ErrorPanel,'Visible','Off'); % --- Executes on button press in NewFigCheckBox. function NewFigCheckBox_Callback(hObject, eventdata, handles) % hObject handle to NewFigCheckBox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of NewFigCheckBox % -------------------------------------------------------------------- function AboutMenu_Callback(hObject, eventdata, handles) % hObject handle to AboutMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) web('GaborFilterDesighnNikAbout.htm'); % -------------------------------------------------------------------- function HelpMenu_Callback(hObject, eventdata, handles) % hObject handle to HelpMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) web('GaborFilterDesighnNikHelp.htm'); %% Servise sub functions function scaled_mat=Scale2Uint(temp) % rescale data to be in margins of UINT8[0-255] temp=double(temp); temp_min=min(temp(:)); temp_max=max(temp(:)); temp=temp-temp_min; temp=255*temp/(temp_max-temp_min); scaled_mat=uint8(temp);
github
jacksky64/imageProcessing-master
smoothn.m
.m
imageProcessing-master/smoothn/smoothn.m
26,704
utf_8
f99199dd381890addc2512f2f23899cc
function [z,s,exitflag] = smoothn(varargin) %SMOOTHN Robust spline smoothing for 1-D to N-D data. % SMOOTHN provides a fast, automatized and robust discretized spline % smoothing for data of arbitrary dimension. % % Z = SMOOTHN(Y) automatically smoothes the uniformly-sampled array Y. Y % can be any N-D noisy array (time series, images, 3D data,...). Non % finite data (NaN or Inf) are treated as missing values. % % Z = SMOOTHN(Y,S) smoothes the array Y using the smoothing parameter S. % S must be a real positive scalar. The larger S is, the smoother the % output will be. If the smoothing parameter S is omitted (see previous % option) or empty (i.e. S = []), it is automatically determined by % minimizing the generalized cross-validation (GCV) score. % % Z = SMOOTHN(Y,W) or Z = SMOOTHN(Y,W,S) smoothes Y using a weighting % array W of positive values, that must have the same size as Y. Note % that a nil weight corresponds to a missing value. % % If you want to smooth a vector field or multicomponent data, Y must be % a cell array. For example, if you need to smooth a 3-D vectorial flow % (Vx,Vy,Vz), use Y = {Vx,Vy,Vz}. The output Z is also a cell array which % contains the smoothed components. See examples 5 to 8 below. % % [Z,S] = SMOOTHN(...) also returns the calculated value for the % smoothness parameter S so that you can fine-tune the smoothing % subsequently if needed. % % 1) Robust smoothing % ------------------- % Z = SMOOTHN(...,'robust') carries out a robust smoothing that minimizes % the influence of outlying data. % % An iteration process is used with the 'ROBUST' option, or in the % presence of weighted and/or missing values. Z = SMOOTHN(...,OPTIONS) % smoothes with the termination parameters specified in the structure % OPTIONS. OPTIONS is a structure of optional parameters that change the % default smoothing properties. It must be last input argument. % --- % The structure OPTIONS can contain the following fields: % ----------------- % OPTIONS.TolZ: Termination tolerance on Z (default = 1e-3), % OPTIONS.TolZ must be in ]0,1[ % OPTIONS.MaxIter: Maximum number of iterations allowed % (default = 100) % OPTIONS.Initial: Initial value for the iterative process % (default = original data, Y) % OPTIONS.Weight: Weight function for robust smoothing: % 'bisquare' (default), 'talworth' or 'cauchy' % ----------------- % % [Z,S,EXITFLAG] = SMOOTHN(...) returns a boolean value EXITFLAG that % describes the exit condition of SMOOTHN: % 1 SMOOTHN converged. % 0 Maximum number of iterations was reached. % % 2) Different spacing increments % ------------------------------- % SMOOTHN, by default, assumes that the spacing increments are constant % and equal in all the directions (i.e. dx = dy = dz = ...). If the % increments differ from one direction to the other, use the following % field in OPTIONS: % OPTIONS.Spacing' = [d1 d2 d3...], % where dI represents the spacing between points in the Ith dimension. % % Important note: d1 is the spacing increment for the first % non-singleton dimension (i.e. the vertical direction for matrices). % % 3) References (please refer to the two following papers) % ------------- % 1) Garcia D, Robust smoothing of gridded data in one and higher % dimensions with missing values. Computational Statistics & Data % Analysis, 2010;54:1167-1178. % <a % href="matlab:web('http://www.biomecardio.com/pageshtm/publi/csda10.pdf')">PDF download</a> % 2) Garcia D, A fast all-in-one method for automated post-processing of % PIV data. Exp Fluids, 2011;50:1247-1259. % <a % href="matlab:web('http://www.biomecardio.com/pageshtm/publi/media11.pdf')">PDF download</a> % % Examples: % -------- % %--- Example #1: smooth a curve --- % x = linspace(0,100,2^8); % y = cos(x/10)+(x/50).^2 + randn(size(x))/10; % y([70 75 80]) = [5.5 5 6]; % z = smoothn(y); % Regular smoothing % zr = smoothn(y,'robust'); % Robust smoothing % subplot(121), plot(x,y,'r.',x,z,'k','LineWidth',2) % axis square, title('Regular smoothing') % subplot(122), plot(x,y,'r.',x,zr,'k','LineWidth',2) % axis square, title('Robust smoothing') % % %--- Example #2: smooth a surface --- % xp = 0:.02:1; % [x,y] = meshgrid(xp); % f = exp(x+y) + sin((x-2*y)*3); % fn = f + randn(size(f))*0.5; % fs = smoothn(fn); % subplot(121), surf(xp,xp,fn), zlim([0 8]), axis square % subplot(122), surf(xp,xp,fs), zlim([0 8]), axis square % % %--- Example #3: smooth an image with missing data --- % n = 256; % y0 = peaks(n); % y = y0 + randn(size(y0))*2; % I = randperm(n^2); % y(I(1:n^2*0.5)) = NaN; % lose 1/2 of data % y(40:90,140:190) = NaN; % create a hole % z = smoothn(y); % smooth data % subplot(2,2,1:2), imagesc(y), axis equal off % title('Noisy corrupt data') % subplot(223), imagesc(z), axis equal off % title('Recovered data ...') % subplot(224), imagesc(y0), axis equal off % title('... compared with the actual data') % % %--- Example #4: smooth volumetric data --- % [x,y,z] = meshgrid(-2:.2:2); % xslice = [-0.8,1]; yslice = 2; zslice = [-2,0]; % vn = x.*exp(-x.^2-y.^2-z.^2) + randn(size(x))*0.06; % subplot(121), slice(x,y,z,vn,xslice,yslice,zslice,'cubic') % title('Noisy data') % v = smoothn(vn); % subplot(122), slice(x,y,z,v,xslice,yslice,zslice,'cubic') % title('Smoothed data') % % %--- Example #5: smooth a cardioid --- % t = linspace(0,2*pi,1000); % x = 2*cos(t).*(1-cos(t)) + randn(size(t))*0.1; % y = 2*sin(t).*(1-cos(t)) + randn(size(t))*0.1; % z = smoothn({x,y}); % plot(x,y,'r.',z{1},z{2},'k','linewidth',2) % axis equal tight % % %--- Example #6: smooth a 3-D parametric curve --- % t = linspace(0,6*pi,1000); % x = sin(t) + 0.1*randn(size(t)); % y = cos(t) + 0.1*randn(size(t)); % z = t + 0.1*randn(size(t)); % u = smoothn({x,y,z}); % plot3(x,y,z,'r.',u{1},u{2},u{3},'k','linewidth',2) % axis tight square % % %--- Example #7: smooth a 2-D vector field --- % [x,y] = meshgrid(linspace(0,1,24)); % Vx = cos(2*pi*x+pi/2).*cos(2*pi*y); % Vy = sin(2*pi*x+pi/2).*sin(2*pi*y); % Vx = Vx + sqrt(0.05)*randn(24,24); % adding Gaussian noise % Vy = Vy + sqrt(0.05)*randn(24,24); % adding Gaussian noise % I = randperm(numel(Vx)); % Vx(I(1:30)) = (rand(30,1)-0.5)*5; % adding outliers % Vy(I(1:30)) = (rand(30,1)-0.5)*5; % adding outliers % Vx(I(31:60)) = NaN; % missing values % Vy(I(31:60)) = NaN; % missing values % Vs = smoothn({Vx,Vy},'robust'); % automatic smoothing % subplot(121), quiver(x,y,Vx,Vy,2.5), axis square % title('Noisy velocity field') % subplot(122), quiver(x,y,Vs{1},Vs{2}), axis square % title('Smoothed velocity field') % % %--- Example #8: smooth a 3-D vector field --- % load wind % original 3-D flow % % -- Create noisy data % % Gaussian noise % un = u + randn(size(u))*8; % vn = v + randn(size(v))*8; % wn = w + randn(size(w))*8; % % Add some outliers % I = randperm(numel(u)) < numel(u)*0.025; % un(I) = (rand(1,nnz(I))-0.5)*200; % vn(I) = (rand(1,nnz(I))-0.5)*200; % wn(I) = (rand(1,nnz(I))-0.5)*200; % % -- Visualize the noisy flow (see CONEPLOT documentation) % figure, title('Noisy 3-D vectorial flow') % xmin = min(x(:)); xmax = max(x(:)); % ymin = min(y(:)); ymax = max(y(:)); % zmin = min(z(:)); % daspect([2,2,1]) % xrange = linspace(xmin,xmax,8); % yrange = linspace(ymin,ymax,8); % zrange = 3:4:15; % [cx cy cz] = meshgrid(xrange,yrange,zrange); % k = 0.1; % hcones = coneplot(x,y,z,un*k,vn*k,wn*k,cx,cy,cz,0); % set(hcones,'FaceColor','red','EdgeColor','none') % hold on % wind_speed = sqrt(un.^2 + vn.^2 + wn.^2); % hsurfaces = slice(x,y,z,wind_speed,[xmin,xmax],ymax,zmin); % set(hsurfaces,'FaceColor','interp','EdgeColor','none') % hold off % axis tight; view(30,40); axis off % camproj perspective; camzoom(1.5) % camlight right; lighting phong % set(hsurfaces,'AmbientStrength',.6) % set(hcones,'DiffuseStrength',.8) % % -- Smooth the noisy flow % Vs = smoothn({un,vn,wn},'robust'); % % -- Display the result % figure, title('3-D flow smoothed by SMOOTHN') % daspect([2,2,1]) % hcones = coneplot(x,y,z,Vs{1}*k,Vs{2}*k,Vs{3}*k,cx,cy,cz,0); % set(hcones,'FaceColor','red','EdgeColor','none') % hold on % wind_speed = sqrt(Vs{1}.^2 + Vs{2}.^2 + Vs{3}.^2); % hsurfaces = slice(x,y,z,wind_speed,[xmin,xmax],ymax,zmin); % set(hsurfaces,'FaceColor','interp','EdgeColor','none') % hold off % axis tight; view(30,40); axis off % camproj perspective; camzoom(1.5) % camlight right; lighting phong % set(hsurfaces,'AmbientStrength',.6) % set(hcones,'DiffuseStrength',.8) % % See also SMOOTH1Q, DCTN, IDCTN. % % -- Damien Garcia -- 2009/03, revised 2014/02 % website: <a % href="matlab:web('http://www.biomecardio.com')">www.BiomeCardio.com</a> %% Check input arguments error(nargchk(1,5,nargin)); OPTIONS = struct; NArgIn = nargin; if isstruct(varargin{end}) % SMOOTHN(...,OPTIONS) OPTIONS = varargin{end}; NArgIn = NArgIn-1; end idx = cellfun(@ischar,varargin); if any(idx) % SMOOTHN(...,'robust',...) assert(sum(idx)==1 && strcmpi(varargin{idx},'robust'),... 'Wrong syntax. Read the help text for instructions.') isrobust = true; assert(find(idx)==NArgIn,... 'Wrong syntax. Read the help text for instructions.') NArgIn = NArgIn-1; else isrobust = false; end %% Test & prepare the variables %--- % y = array to be smoothed y = varargin{1}; if ~iscell(y), y = {y}; end sizy = size(y{1}); ny = numel(y); % number of y components for i = 1:ny assert(isequal(sizy,size(y{i})),... 'Data arrays in Y must have the same size.') y{i} = double(y{i}); end noe = prod(sizy); % number of elements if noe==1, z = y{1}; s = []; exitflag = true; return, end %--- % Smoothness parameter and weights W = ones(sizy); s = []; if NArgIn==2 if isempty(varargin{2}) || isscalar(varargin{2}) % smoothn(y,s) s = varargin{2}; % smoothness parameter else % smoothn(y,W) W = varargin{2}; % weight array end elseif NArgIn==3 % smoothn(y,W,s) W = varargin{2}; % weight array s = varargin{3}; % smoothness parameter end assert(isnumeric(W),'W must be a numeric array') assert(isnumeric(s),'S must be a numeric scalar') assert(isequal(size(W),sizy),... 'Arrays for data and weights (Y and W) must have same size.') assert(isempty(s) || (isscalar(s) && s>0),... 'The smoothing parameter S must be a scalar >0') %--- % Field names in the structure OPTIONS OptionNames = fieldnames(OPTIONS); idx = ismember(OptionNames,... {'TolZ','MaxIter','Initial','Weight','Spacing','Order'}); assert(all(idx),... ['''' OptionNames{find(~idx,1)} ''' is not a valid field name for OPTIONS.']) %--- % "Maximal number of iterations" criterion if ~ismember('MaxIter',OptionNames) OPTIONS.MaxIter = 100; % default value for MaxIter end assert(isnumeric(OPTIONS.MaxIter) && isscalar(OPTIONS.MaxIter) &&... OPTIONS.MaxIter>=1 && OPTIONS.MaxIter==round(OPTIONS.MaxIter),... 'OPTIONS.MaxIter must be an integer >=1') %--- % "Tolerance on smoothed output" criterion if ~ismember('TolZ',OptionNames) OPTIONS.TolZ = 1e-3; % default value for TolZ end assert(isnumeric(OPTIONS.TolZ) && isscalar(OPTIONS.TolZ) &&... OPTIONS.TolZ>0 && OPTIONS.TolZ<1,'OPTIONS.TolZ must be in ]0,1[') %--- % "Initial Guess" criterion if ~ismember('Initial',OptionNames) isinitial = false; else isinitial = true; z0 = OPTIONS.Initial; if ~iscell(z0), z0 = {z0}; end nz0 = numel(z0); % number of y components assert(nz0==ny,... 'OPTIONS.Initial must contain a valid initial guess for Z') for i = 1:nz0 assert(isequal(sizy,size(z0{i})),... 'OPTIONS.Initial must contain a valid initial guess for Z') z0{i} = double(z0{i}); end end %--- % "Weight function" criterion (for robust smoothing) if ~ismember('Weight',OptionNames) OPTIONS.Weight = 'bisquare'; % default weighting function else assert(ischar(OPTIONS.Weight),... 'A valid weight function (OPTIONS.Weight) must be chosen') assert(any(ismember(lower(OPTIONS.Weight),... {'bisquare','talworth','cauchy'})),... 'The weight function must be ''bisquare'', ''cauchy'' or '' talworth''.') end %--- % "Order" criterion (by default m = 2) % Note: m = 0 is of course not recommended! if ~ismember('Order',OptionNames) m = 2; % order else m = OPTIONS.Order; if ~ismember(m,0:2); error('MATLAB:smoothn:IncorrectOrder',... 'The order (OPTIONS.order) must be 0, 1 or 2.') end end %--- % "Spacing" criterion d = ndims(y{1}); if ~ismember('Spacing',OptionNames) dI = ones(1,d); % spacing increment else dI = OPTIONS.Spacing; assert(isnumeric(dI) && length(dI)==d,... 'A valid spacing (OPTIONS.Spacing) must be chosen') end dI = dI/max(dI); %--- % Weights. Zero weights are assigned to not finite values (Inf or NaN), % (Inf/NaN values = missing data). IsFinite = isfinite(y{1}); for i = 2:ny, IsFinite = IsFinite & isfinite(y{i}); end nof = nnz(IsFinite); % number of finite elements W = W.*IsFinite; assert(all(W(:)>=0),'Weights must all be >=0') W = W/max(W(:)); %--- % Weighted or missing data? isweighted = any(W(:)<1); %--- % Automatic smoothing? isauto = isempty(s); %% Create the Lambda tensor %--- % Lambda contains the eingenvalues of the difference matrix used in this % penalized least squares process (see CSDA paper for details) d = ndims(y{1}); Lambda = zeros(sizy); for i = 1:d siz0 = ones(1,d); siz0(i) = sizy(i); Lambda = bsxfun(@plus,Lambda,... (2-2*cos(pi*(reshape(1:sizy(i),siz0)-1)/sizy(i)))/dI(i)^2); end if ~isauto, Gamma = 1./(1+s*Lambda.^m); end %% Upper and lower bound for the smoothness parameter % The average leverage (h) is by definition in [0 1]. Weak smoothing occurs % if h is close to 1, while over-smoothing appears when h is near 0. Upper % and lower bounds for h are given to avoid under- or over-smoothing. See % equation relating h to the smoothness parameter for m = 2 (Equation #12 % in the referenced CSDA paper). N = sum(sizy~=1); % tensor rank of the y-array hMin = 1e-6; hMax = 0.99; if m==0 % Not recommended. For mathematical purpose only. sMinBnd = 1/hMax^(1/N)-1; sMaxBnd = 1/hMin^(1/N)-1; elseif m==1 sMinBnd = (1/hMax^(2/N)-1)/4; sMaxBnd = (1/hMin^(2/N)-1)/4; elseif m==2 sMinBnd = (((1+sqrt(1+8*hMax^(2/N)))/4/hMax^(2/N))^2-1)/16; sMaxBnd = (((1+sqrt(1+8*hMin^(2/N)))/4/hMin^(2/N))^2-1)/16; end %% Initialize before iterating %--- Wtot = W; %--- Initial conditions for z if isweighted %--- With weighted/missing data % An initial guess is provided to ensure faster convergence. For that % purpose, a nearest neighbor interpolation followed by a coarse % smoothing are performed. %--- if isinitial % an initial guess (z0) has been already given z = z0; else z = InitialGuess(y,IsFinite); end else z = cell(size(y)); for i = 1:ny, z{i} = zeros(sizy); end end %--- z0 = z; for i = 1:ny y{i}(~IsFinite) = 0; % arbitrary values for missing y-data end %--- tol = 1; RobustIterativeProcess = true; RobustStep = 1; nit = 0; DCTy = cell(1,ny); vec = @(x) x(:); %--- Error on p. Smoothness parameter s = 10^p errp = 0.1; opt = optimset('TolX',errp); %--- Relaxation factor RF: to speedup convergence RF = 1 + 0.75*isweighted; %% Main iterative process %--- while RobustIterativeProcess %--- "amount" of weights (see the function GCVscore) aow = sum(Wtot(:))/noe; % 0 < aow <= 1 %--- while tol>OPTIONS.TolZ && nit<OPTIONS.MaxIter nit = nit+1; for i = 1:ny DCTy{i} = dctn(Wtot.*(y{i}-z{i})+z{i}); end if isauto && ~rem(log2(nit),1) %--- % The generalized cross-validation (GCV) method is used. % We seek the smoothing parameter S that minimizes the GCV % score i.e. S = Argmin(GCVscore). % Because this process is time-consuming, it is performed from % time to time (when the step number - nit - is a power of 2) %--- fminbnd(@gcv,log10(sMinBnd),log10(sMaxBnd),opt); end for i = 1:ny z{i} = RF*idctn(Gamma.*DCTy{i}) + (1-RF)*z{i}; end % if no weighted/missing data => tol=0 (no iteration) tol = isweighted*norm(vec([z0{:}]-[z{:}]))/norm(vec([z{:}])); z0 = z; % re-initialization end exitflag = nit<OPTIONS.MaxIter; if isrobust %-- Robust Smoothing: iteratively re-weighted process %--- average leverage h = 1; for k = 1:N if m==0 % not recommended - only for numerical purpose h0 = 1/(1+s/dI(k)^(2^m)); elseif m==1 h0 = 1/sqrt(1+4*s/dI(k)^(2^m)); elseif m==2 h0 = sqrt(1+16*s/dI(k)^(2^m)); h0 = sqrt(1+h0)/sqrt(2)/h0; else error('m must be 0, 1 or 2.') end h = h*h0; end %--- take robust weights into account Wtot = W.*RobustWeights(y,z,IsFinite,h,OPTIONS.Weight); %--- re-initialize for another iterative weighted process isweighted = true; tol = 1; nit = 0; %--- RobustStep = RobustStep+1; RobustIterativeProcess = RobustStep<4; % 3 robust steps are enough. else RobustIterativeProcess = false; % stop the whole process end end %% Warning messages %--- if isauto if abs(log10(s)-log10(sMinBnd))<errp warning('MATLAB:smoothn:SLowerBound',... ['S = ' num2str(s,'%.3e') ': the lower bound for S ',... 'has been reached. Put S as an input variable if required.']) elseif abs(log10(s)-log10(sMaxBnd))<errp warning('MATLAB:smoothn:SUpperBound',... ['S = ' num2str(s,'%.3e') ': the upper bound for S ',... 'has been reached. Put S as an input variable if required.']) end end if nargout<3 && ~exitflag warning('MATLAB:smoothn:MaxIter',... ['Maximum number of iterations (' int2str(OPTIONS.MaxIter) ') has been exceeded. ',... 'Increase MaxIter option (OPTIONS.MaxIter) or decrease TolZ (OPTIONS.TolZ) value.']) end if numel(z)==1, z = z{:}; end %% GCV score %--- function GCVscore = gcv(p) % Search the smoothing parameter s that minimizes the GCV score %--- s = 10^p; Gamma = 1./(1+s*Lambda.^m); %--- RSS = Residual sum-of-squares RSS = 0; if aow>0.9 % aow = 1 means that all of the data are equally weighted % very much faster: does not require any inverse DCT for kk = 1:ny RSS = RSS + norm(DCTy{kk}(:).*(Gamma(:)-1))^2; end else % take account of the weights to calculate RSS: for kk = 1:ny yhat = idctn(Gamma.*DCTy{kk}); RSS = RSS + norm(sqrt(Wtot(IsFinite)).*... (y{kk}(IsFinite)-yhat(IsFinite)))^2; end end %--- TrH = sum(Gamma(:)); GCVscore = RSS/nof/(1-TrH/noe)^2; end end function W = RobustWeights(y,z,I,h,wstr) % One seeks the weights for robust smoothing... ABS = @(x) sqrt(sum(abs(x).^2,2)); r = cellfun(@minus,y,z,'UniformOutput',0); % residuals r = cellfun(@(x) x(:),r,'UniformOutput',0); rI = cell2mat(cellfun(@(x) x(I),r,'UniformOutput',0)); MMED = median(rI); % marginal median AD = ABS(bsxfun(@minus,rI,MMED)); % absolute deviation MAD = median(AD); % median absolute deviation %-- Studentized residuals u = ABS(cell2mat(r))/(1.4826*MAD)/sqrt(1-h); u = reshape(u,size(I)); switch lower(wstr) case 'cauchy' c = 2.385; W = 1./(1+(u/c).^2); % Cauchy weights case 'talworth' c = 2.795; W = u<c; % Talworth weights case 'bisquare' c = 4.685; W = (1-(u/c).^2).^2.*((u/c)<1); % bisquare weights otherwise error('MATLAB:smoothn:IncorrectWeights',... 'A valid weighting function must be chosen') end W(isnan(W)) = 0; % NOTE: % ---- % The RobustWeights subfunction looks complicated since we work with cell % arrays. For better clarity, here is how it would look like without the % use of cells. Much more readable, isn't it? % % function W = RobustWeights(y,z,I,h) % % weights for robust smoothing. % r = y-z; % residuals % MAD = median(abs(r(I)-median(r(I)))); % median absolute deviation % u = abs(r/(1.4826*MAD)/sqrt(1-h)); % studentized residuals % c = 4.685; W = (1-(u/c).^2).^2.*((u/c)<1); % bisquare weights % W(isnan(W)) = 0; % end end %% Initial Guess with weighted/missing data function z = InitialGuess(y,I) ny = numel(y); %-- nearest neighbor interpolation (in case of missing values) if any(~I(:)) z = cell(size(y)); if license('test','image_toolbox') for i = 1:ny [z{i},L] = bwdist(I); z{i} = y{i}; z{i}(~I) = y{i}(L(~I)); end else % If BWDIST does not exist, NaN values are all replaced with the % same scalar. The initial guess is not optimal and a warning % message thus appears. z = y; for i = 1:ny z{i}(~I) = mean(y{i}(I)); end warning('MATLAB:smoothn:InitialGuess',... ['BWDIST (Image Processing Toolbox) does not exist. ',... 'The initial guess may not be optimal; additional',... ' iterations can thus be required to ensure complete',... ' convergence. Increase ''MaxIter'' criterion if necessary.']) end else z = y; end %-- coarse fast smoothing using one-tenth of the DCT coefficients siz = size(z{1}); z = cellfun(@(x) dctn(x),z,'UniformOutput',0); for k = 1:ndims(z{1}) for i = 1:ny z{i}(ceil(siz(k)/10)+1:end,:) = 0; z{i} = reshape(z{i},circshift(siz,[0 1-k])); z{i} = shiftdim(z{i},1); end end z = cellfun(@(x) idctn(x),z,'UniformOutput',0); end %% DCTN function y = dctn(y) %DCTN N-D discrete cosine transform. % Y = DCTN(X) returns the discrete cosine transform of X. The array Y is % the same size as X and contains the discrete cosine transform % coefficients. This transform can be inverted using IDCTN. % % Reference % --------- % Narasimha M. et al, On the computation of the discrete cosine % transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936. % % Example % ------- % RGB = imread('autumn.tif'); % I = rgb2gray(RGB); % J = dctn(I); % imshow(log(abs(J)),[]), colormap(jet), colorbar % % The commands below set values less than magnitude 10 in the DCT matrix % to zero, then reconstruct the image using the inverse DCT. % % J(abs(J)<10) = 0; % K = idctn(J); % figure, imshow(I) % figure, imshow(K,[0 255]) % % -- Damien Garcia -- 2008/06, revised 2011/11 % -- www.BiomeCardio.com -- y = double(y); sizy = size(y); y = squeeze(y); dimy = ndims(y); % Some modifications are required if Y is a vector if isvector(y) dimy = 1; if size(y,1)==1, y = y.'; end end % Weighting vectors w = cell(1,dimy); for dim = 1:dimy n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim); w{dim} = exp(1i*(0:n-1)'*pi/2/n); end % --- DCT algorithm --- if ~isreal(y) y = complex(dctn(real(y)),dctn(imag(y))); else for dim = 1:dimy siz = size(y); n = siz(1); y = y([1:2:n 2*floor(n/2):-2:2],:); y = reshape(y,n,[]); y = y*sqrt(2*n); y = ifft(y,[],1); y = bsxfun(@times,y,w{dim}); y = real(y); y(1,:) = y(1,:)/sqrt(2); y = reshape(y,siz); y = shiftdim(y,1); end end y = reshape(y,sizy); end %% IDCTN function y = idctn(y) %IDCTN N-D inverse discrete cosine transform. % X = IDCTN(Y) inverts the N-D DCT transform, returning the original % array if Y was obtained using Y = DCTN(X). % % Reference % --------- % Narasimha M. et al, On the computation of the discrete cosine % transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936. % % Example % ------- % RGB = imread('autumn.tif'); % I = rgb2gray(RGB); % J = dctn(I); % imshow(log(abs(J)),[]), colormap(jet), colorbar % % The commands below set values less than magnitude 10 in the DCT matrix % to zero, then reconstruct the image using the inverse DCT. % % J(abs(J)<10) = 0; % K = idctn(J); % figure, imshow(I) % figure, imshow(K,[0 255]) % % See also DCTN, IDSTN, IDCT, IDCT2, IDCT3. % % -- Damien Garcia -- 2009/04, revised 2011/11 % -- www.BiomeCardio.com -- y = double(y); sizy = size(y); y = squeeze(y); dimy = ndims(y); % Some modifications are required if Y is a vector if isvector(y) dimy = 1; if size(y,1)==1 y = y.'; end end % Weighing vectors w = cell(1,dimy); for dim = 1:dimy n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim); w{dim} = exp(1i*(0:n-1)'*pi/2/n); end % --- IDCT algorithm --- if ~isreal(y) y = complex(idctn(real(y)),idctn(imag(y))); else for dim = 1:dimy siz = size(y); n = siz(1); y = reshape(y,n,[]); y = bsxfun(@times,y,w{dim}); y(1,:) = y(1,:)/sqrt(2); y = ifft(y,[],1); y = real(y*sqrt(2*n)); I = (1:n)*0.5+0.5; I(2:2:end) = n-I(1:2:end-1)+1; y = y(I,:); y = reshape(y,siz); y = shiftdim(y,1); end end y = reshape(y,sizy); end
github
jayinai/pva-faster-rcnn-master
voc_eval.m
.m
pva-faster-rcnn-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
1,332
utf_8
3ee1d5373b091ae4ab79d26ab657c962
function res = voc_eval(path, comp_id, test_set, output_dir) VOCopts = get_voc_opts(path); VOCopts.testset = test_set; for i = 1:length(VOCopts.classes) cls = VOCopts.classes{i}; res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir); end fprintf('\n~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Results:\n'); aps = [res(:).ap]'; fprintf('%.1f\n', aps * 100); fprintf('%.1f\n', mean(aps) * 100); fprintf('~~~~~~~~~~~~~~~~~~~~\n'); function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir) test_set = VOCopts.testset; year = VOCopts.dataset(4:end); addpath(fullfile(VOCopts.datadir, 'VOCcode')); res_fn = sprintf(VOCopts.detrespath, comp_id, cls); recall = []; prec = []; ap = 0; ap_auc = 0; do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test'); if do_eval % Bug in VOCevaldet requires that tic has been called first tic; [recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true); ap_auc = xVOCap(recall, prec); % force plot limits ylim([0 1]); xlim([0 1]); print(gcf, '-djpeg', '-r0', ... [output_dir '/' cls '_pr.jpg']); end fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc); res.recall = recall; res.prec = prec; res.ap = ap; res.ap_auc = ap_auc; save([output_dir '/' cls '_pr.mat'], ... 'res', 'recall', 'prec', 'ap', 'ap_auc'); rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
github
OpenDataCyprus/dland-master
savejson.m
.m
dland-master/supporting_scripts/matlab-tools/jsonlab-1.2/jsonlab/savejson.m
18,983
utf_8
2f510ad749556cadd303786e2549f30a
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id$ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array, % class instance). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.SingletArray [0|1]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.SingletCell [1|0]: if 1, always enclose a cell with "[]" % even it has only one element; if 0, brackets % are ignored when a cell has only 1 element. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('filename',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); if(isfield(opt,'norowbracket')) warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)'); if(~isfield(opt,'singletarray')) opt.singletarray=not(opt.norowbracket); end end rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ... iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin filename=jsonopt('FileName','',opt); if(~isempty(filename)) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(filename, 'wb'); fwrite(fid,json); else fid = fopen(filename, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); elseif(isobject(item)) txt=matlabobject2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt={}; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; bracketlevel=~jsonopt('singletcell',1,varargin{:}); if(len>bracketlevel) if(~isempty(name)) txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; name=''; else txt={padding0, '[', nl}; end elseif(len==0) if(~isempty(name)) txt={padding0, '"' checkname(name,varargin{:}) '": []'}; name=''; else txt={padding0, '[]'}; end end for i=1:dim(1) if(dim(1)>1) txt(end+1:end+3)={padding2,'[',nl}; end for j=1:dim(2) txt{end+1}=obj2json(name,item{i,j},level+(dim(1)>1)+(len>bracketlevel),varargin{:}); if(j<dim(2)) txt(end+1:end+2)={',' nl}; end end if(dim(1)>1) txt(end+1:end+3)={nl,padding2,']'}; end if(i<dim(1)) txt(end+1:end+2)={',' nl}; end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>bracketlevel) txt(end+1:end+3)={nl,padding0,']'}; end txt = sprintf('%s',txt{:}); %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt={}; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0)); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+forcearray); nl=ws.newline; if(isempty(item)) if(~isempty(name)) txt={padding0, '"', checkname(name,varargin{:}),'": []'}; else txt={padding0, '[]'}; end return; end if(~isempty(name)) if(forcearray) txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; end else if(forcearray) txt={padding0, '[', nl}; end end for j=1:dim(2) if(dim(1)>1) txt(end+1:end+3)={padding2,'[',nl}; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1 && ~forcearray) txt(end+1:end+5)={padding1, '"', checkname(name,varargin{:}),'": {', nl}; else txt(end+1:end+3)={padding1, '{', nl}; end if(~isempty(names)) for e=1:length(names) txt{end+1}=obj2json(names{e},item(i,j).(names{e}),... level+(dim(1)>1)+1+forcearray,varargin{:}); if(e<length(names)) txt{end+1}=','; end txt{end+1}=nl; end end txt(end+1:end+2)={padding1,'}'}; if(i<dim(1)) txt(end+1:end+2)={',' nl}; end end if(dim(1)>1) txt(end+1:end+3)={nl,padding2,']'}; end if(j<dim(2)) txt(end+1:end+2)={',' nl}; end end if(forcearray) txt(end+1:end+3)={nl,padding0,']'}; end txt = sprintf('%s',txt{:}); %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt={}; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt={padding1, '"', checkname(name,varargin{:}),'": [', nl}; end else if(len>1) txt={padding1, '[', nl}; end end for e=1:len val=escapejsonstring(item(e,:)); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt(end+1:end+2)={padding1, obj}; else txt(end+1:end+4)={padding0,'"',val,'"'}; end if(e==len) sep=''; end txt{end+1}=sep; end if(len>1) txt(end+1:end+3)={nl,padding1,']'}; end txt = sprintf('%s',txt{:}); %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... (isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matlabobject2json(name,item,level,varargin) if numel(item) == 0 %empty object st = struct(); else % "st = struct(item);" would produce an inmutable warning, because it % make the protected and private properties visible. Instead we get the % visible properties propertynames = properties(item); for p = 1:numel(propertynames) for o = numel(item):-1:1 % aray of objects st(o).(propertynames{p}) = item(o).(propertynames{p}); end end end txt=struct2json(name,st,level,varargin{:}); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\\','\"','\/','\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\$1'); else escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\\$1'); end
github
OpenDataCyprus/dland-master
loadjson.m
.m
dland-master/supporting_scripts/matlab-tools/jsonlab-1.2/jsonlab/loadjson.m
16,145
ibm852
7582071c5bd7f5e5f74806ce191a9078
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id$ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once')) string=fname; elseif(exist(fname,'file')) try string = fileread(fname); catch try string = urlread(['file://',fname]); catch string = urlread(['file://',fullfile(pwd,fname)]); end end else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); object.(valid_field(str))=val; if next_char == '}' break; end parse_char(','); end end parse_char('}'); if(isstruct(object)) object=struct2jdata(object); end %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=-1; if(isfield(varargin{1},'progressbar_')) pbar=varargin{1}.progressbar_; end if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ismatrix(object)) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len pos=skip_whitespace(pos,inStr,len); if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; pos=skip_whitespace(pos,inStr,len); end %%------------------------------------------------------------------------- function c = next_char global pos inStr len pos=skip_whitespace(pos,inStr,len); if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function newpos=skip_whitespace(pos,inStr,len) newpos=pos; while newpos <= len && isspace(inStr(newpos)) newpos = newpos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos); keyboard; pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr isoct currstr=inStr(pos:min(pos+30,end)); if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len if(isfield(varargin{1},'progressbar_')) waitbar(pos/len,varargin{1}.progressbar_,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
OpenDataCyprus/dland-master
loadubjson.m
.m
dland-master/supporting_scripts/matlab-tools/jsonlab-1.2/jsonlab/loadubjson.m
13,300
utf_8
b15e959f758c5c2efa2711aa79c443fc
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id$ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or % earlier versions (JSONLab 1.0 final or earlier), % the "name" tag is treated as a string. To load % these UBJSON data, you need to manually set this % flag to 1. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 if(jsonopt('NameIsString',0,varargin{:})) str = parseStr(varargin{:}); else str = parse_name(varargin{:}); end if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; object.(valid_field(str))=val; if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end if(isstruct(object)) object=struct2jdata(object); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data, adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object, adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object, adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ismatrix(object)) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parse_name(varargin) global pos inStr bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of name'); end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
OpenDataCyprus/dland-master
saveubjson.m
.m
dland-master/supporting_scripts/matlab-tools/jsonlab-1.2/jsonlab/saveubjson.m
17,723
utf_8
3414421172c05225dfbd4a9c8c76e6b3
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id$ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array, % class instance) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.SingletArray [0|1]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.SingletCell [1|0]: if 1, always enclose a cell with "[]" % even it has only one element; if 0, brackets % are ignored when a cell has only 1 element. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('filename',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); if(isfield(opt,'norowbracket')) warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)'); if(~isfield(opt,'singletarray')) opt.singletarray=not(opt.norowbracket); end end rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ... iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin filename=jsonopt('FileName','',opt); if(~isempty(filename)) fid = fopen(filename, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); elseif(isobject(item)) txt=matlabobject2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end bracketlevel=~jsonopt('singletcell',1,varargin{:}); len=numel(item); % let's handle 1D cell first if(len>bracketlevel) if(~isempty(name)) txt=[N_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[N_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>bracketlevel),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>bracketlevel) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0)); if(~isempty(name)) if(forcearray) txt=[N_(checkname(name,varargin{:})) '[']; end else if(forcearray) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1 && ~forcearray) txt=[txt N_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),... level+(dim(1)>1)+1+forcearray,varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(forcearray) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[N_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for e=1:len val=item(e,:); if(len==1) obj=[N_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... (isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[N_(checkname(name,varargin{:})),'Z']; return; else txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[N_(checkname(name,varargin{:})) numtxt]; else txt=[N_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,N_('_ArrayIsComplex_'),'T']; end txt=[txt,N_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,N_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,N_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,N_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,N_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,N_('_ArrayIsComplex_'),'T']; txt=[txt,N_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matlabobject2ubjson(name,item,level,varargin) if numel(item) == 0 %empty object st = struct(); else % "st = struct(item);" would produce an inmutable warning, because it % make the protected and private properties visible. Instead we get the % visible properties propertynames = properties(item); for p = 1:numel(propertynames) for o = numel(item):-1:1 % aray of objects st(o).(propertynames{p}) = item(o).(propertynames{p}); end end end txt=struct2ubjson(name,st,level,varargin{:}); %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(id~=0)) error('high-precision data is not yet supported'); end key='iIlL'; type=key(id~=0); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=N_(str) val=[I_(int32(length(str))) str]; %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
jacoxu/2016NLPCC_Stance_Detection-master
LGE.m
.m
2016NLPCC_Stance_Detection-master/code/LSA_and_LPI_and_LE_matlab/LPI/LGE.m
8,862
utf_8
d32a983d6516d8bc40b016ed26d59a7e
function [eigvector, eigvalue] = LGE(W, D, options, data) % LGE: Linear Graph Embedding % % [eigvector, eigvalue] = LGE(W, D, options, data) % % Input: % data - data matrix. Each row vector of data is a % sample vector. % W - Affinity graph matrix. % D - Constraint graph matrix. % LGE solves the optimization problem of % a* = argmax (a'data'WXa)/(a'data'DXa) % Default: D = I % % options - Struct value in Matlab. The fields in options % that can be set: % % ReducedDim - The dimensionality of the reduced % subspace. If 0, all the dimensions % will be kept. Default is 30. % % Regu - 1: regularized solution, % a* = argmax (a'X'WXa)/(a'X'DXa+ReguAlpha*I) % 0: solve the sinularity problem by SVD (PCA) % Default: 0 % % ReguAlpha - The regularization parameter. Valid % when Regu==1. Default value is 0.1. % % ReguType - 'Ridge': Tikhonov regularization % 'Custom': User provided % regularization matrix % Default: 'Ridge' % regularizerR - (nFea x nFea) regularization % matrix which should be provided % if ReguType is 'Custom'. nFea is % the feature number of data % matrix % % PCARatio - The percentage of principal % component kept in the PCA % step. The percentage is % calculated based on the % eigenvalue. Default is 1 % (100%, all the non-zero % eigenvalues will be kept. % If PCARatio > 1, the PCA step % will keep exactly PCARatio principle % components (does not exceed the % exact number of non-zero components). % % % Output: % eigvector - Each column is an embedding function, for a new % sample vector (row vector) x, y = x*eigvector % will be the embedding result of x. % eigvalue - The sorted eigvalue of the eigen-problem. % elapse - Time spent on different steps % % % % Examples: % % See also LPP, NPE, IsoProjection, LSDA. % % %Reference: % % 1. Deng Cai, Xiaofei He, Jiawei Han, "Spectral Regression for Efficient % Regularized Subspace Learning", IEEE International Conference on % Computer Vision (ICCV), Rio de Janeiro, Brazil, Oct. 2007. % % 2. Deng Cai, Xiaofei He, Yuxiao Hu, Jiawei Han, and Thomas Huang, % "Learning a Spatially Smooth Subspace for Face Recognition", CVPR'2007 % % 3. Deng Cai, Xiaofei He, Jiawei Han, "Spectral Regression: A Unified % Subspace Learning Framework for Content-Based Image Retrieval", ACM % Multimedia 2007, Augsburg, Germany, Sep. 2007. % % 4. Deng Cai, "Spectral Regression: A Regression Framework for % Efficient Regularized Subspace Learning", PhD Thesis, Department of % Computer Science, UIUC, 2009. % % version 3.0 --Dec/2011 % version 2.1 --June/2007 % version 2.0 --May/2007 % version 1.0 --Sep/2006 % % Written by Deng Cai (dengcai AT gmail.com) % MAX_MATRIX_SIZE = 1600; % You can change this number according your machine computational power EIGVECTOR_RATIO = 0.1; % You can change this number according your machine computational power if (~exist('options','var')) options = []; end ReducedDim = 30; if isfield(options,'ReducedDim') ReducedDim = options.ReducedDim; end if ~isfield(options,'Regu') || ~options.Regu bPCA = 1; if ~isfield(options,'PCARatio') options.PCARatio = 1; end else bPCA = 0; if ~isfield(options,'ReguType') options.ReguType = 'Ridge'; end if ~isfield(options,'ReguAlpha') options.ReguAlpha = 0.1; end end bD = 1; if ~exist('D','var') || isempty(D) bD = 0; end [nSmp,nFea] = size(data); if size(W,1) ~= nSmp error('W and data mismatch!'); end if bD && (size(D,1) ~= nSmp) error('D and data mismatch!'); end bChol = 0; if bPCA && (nSmp > nFea) && (options.PCARatio >= 1) if bD DPrime = data'*D*data; else DPrime = data'*data; end DPrime = full(DPrime); DPrime = max(DPrime,DPrime'); [R,p] = chol(DPrime); if p == 0 bPCA = 0; bChol = 1; end end %====================================== % SVD %====================================== if bPCA [U, S, V] = mySVD(data); [U, S, V]=CutonRatio(U,S,V,options); eigvalue_PCA = full(diag(S)); if bD data = U*S; eigvector_PCA = V; DPrime = data'*D*data; DPrime = max(DPrime,DPrime'); else data = U; eigvector_PCA = V*spdiags(eigvalue_PCA.^-1,0,length(eigvalue_PCA),length(eigvalue_PCA)); end else if ~bChol if bD DPrime = data'*D*data; else DPrime = data'*data; end switch lower(options.ReguType) case {lower('Ridge')} if options.ReguAlpha > 0 for i=1:size(DPrime,1) DPrime(i,i) = DPrime(i,i) + options.ReguAlpha; end end case {lower('Tensor')} if options.ReguAlpha > 0 DPrime = DPrime + options.ReguAlpha*options.regularizerR; end case {lower('Custom')} if options.ReguAlpha > 0 DPrime = DPrime + options.ReguAlpha*options.regularizerR; end otherwise error('ReguType does not exist!'); end DPrime = max(DPrime,DPrime'); end end WPrime = data'*W*data; WPrime = max(WPrime,WPrime'); %====================================== % Generalized Eigen %====================================== dimMatrix = size(WPrime,2); if ReducedDim > dimMatrix ReducedDim = dimMatrix; end if isfield(options,'bEigs') bEigs = options.bEigs; else if (dimMatrix > MAX_MATRIX_SIZE) && (ReducedDim < dimMatrix*EIGVECTOR_RATIO) bEigs = 1; else bEigs = 0; end end if bEigs %disp('use eigs to speed up!'); option = struct('disp',0); if bPCA && ~bD [eigvector, eigvalue] = eigs(WPrime,ReducedDim,'la',option); else if bChol option.cholB = 1; [eigvector, eigvalue] = eigs(WPrime,R,ReducedDim,'la',option); else [eigvector, eigvalue] = eigs(WPrime,DPrime,ReducedDim,'la',option); end end eigvalue = diag(eigvalue); else if bPCA && ~bD [eigvector, eigvalue] = eig(WPrime); else [eigvector, eigvalue] = eig(WPrime,DPrime); end eigvalue = diag(eigvalue); [junk, index] = sort(-eigvalue); eigvalue = eigvalue(index); eigvector = eigvector(:,index); if ReducedDim < size(eigvector,2) eigvector = eigvector(:, 1:ReducedDim); eigvalue = eigvalue(1:ReducedDim); end end if bPCA eigvector = eigvector_PCA*eigvector; end for i = 1:size(eigvector,2) eigvector(:,i) = eigvector(:,i)./norm(eigvector(:,i)); end function [U, S, V]=CutonRatio(U,S,V,options) if ~isfield(options, 'PCARatio') options.PCARatio = 1; end eigvalue_PCA = full(diag(S)); if options.PCARatio > 1 idx = options.PCARatio; if idx < length(eigvalue_PCA) U = U(:,1:idx); V = V(:,1:idx); S = S(1:idx,1:idx); end elseif options.PCARatio < 1 sumEig = sum(eigvalue_PCA); sumEig = sumEig*options.PCARatio; sumNow = 0; for idx = 1:length(eigvalue_PCA) sumNow = sumNow + eigvalue_PCA(idx); if sumNow >= sumEig break; end end U = U(:,1:idx); V = V(:,1:idx); S = S(1:idx,1:idx); end
github
martinarielhartmann/mirtooloct-master
SetGain.m
.m
mirtooloct-master/AuditoryToolbox/SetGain.m
316
utf_8
ee1086fa88ad33019c0d5f97fbe4fc80
% filter = SetGain(filter, desired, f, fs) % Set the gain of a filter (1x5 vector) to any desired gain % at any desired frequency (f). % (c) 1998 Interval Research Corporation function filter = SetGain(filter, desired, f, fs) oldGain = 10^(FreqResp(filter, f, fs)/20); filter(1:3) = filter(1:3)*desired/oldGain;
github
martinarielhartmann/mirtooloct-master
FreqResp.m
.m
mirtooloct-master/AuditoryToolbox/FreqResp.m
358
utf_8
126f81f4aebfed2dcb78c606fdf26621
% mag = FreqResp(filter, f, fs) % Find the frequency response (in dB) of a filter (1x5 vector) at % frequency f and sampling rate fs. % (c) 1998 Interval Research Corporation function mag=FreqResp(filter,f,fs) cf = exp(i*2*pi*f/fs); mag = (filter(3) + filter(2)*cf + filter(1)*cf.^2) ./ ... (filter(5) + filter(4)*cf + cf.^2); mag = 20*log10(abs(mag));
github
martinarielhartmann/mirtooloct-master
SecondOrderFilter.m
.m
mirtooloct-master/AuditoryToolbox/SecondOrderFilter.m
401
utf_8
d07f8051e149ab98df3ca36bc12a0ab6
% filter = SecondOrderFilter(f, q, fs) % Design a second order digital filter with a center frequency of % f, filter quality of q, and digital sampling rate of fs (Hz). % (c) 1998 Interval Research Corporation function filts = SecondOrderFilter(f,q,fs) cft = f'/fs; rho = exp(- pi * cft ./ q'); theta = 2 * pi * cft .* sqrt(1-1 ./(4*q'.^2)); filts = [ ones(size(rho)) -2*rho.*cos(theta) rho.^2 ];
github
martinarielhartmann/mirtooloct-master
test_auditory.m
.m
mirtooloct-master/AuditoryToolbox/test_auditory.m
8,929
utf_8
37ff5eae38fd9f5b0a042b478a00d417
function test_auditory(test) % function test_auditory(test) % Test each of the functions in the Auditory Toolbox. The single argument % is a string, containing the word 'all' or the name of one routine from the % toolbox. This routine defaults to running all tests. There is a pause after % each plot, so be sure to hit the return key so the testing can proceed. % % (c) 1998 Interval Research Corporation if nargin < 1 test = 'all'; end if strcmp(test,'agc') | strcmp(test,'all') disp('agc test'); set_window_size(200, 150); agc(ones(1,20), [.5;.5]) plot(agc(ones(1,30), [.8; .5])); pause; plot(agc(ones(1,30),[.4;.5])); pause; plot(agc(ones(1,30),[.4;.1])); pause; end if strcmp(test,'CorrelogramArray') | strcmp(test,'all') disp('CorrelogramArray test'); u=MakeVowel(4000,FMPoints(4000,120),16000,'u'); soundsc(u,16000) coch=LyonPassiveEar(u,16000,1,4,.25); width = 256; cor=CorrelogramArray(coch,16000,16,width); [pixels frames] = size(cor); colormap(1-gray); for j=1:frames imagesc(reshape(cor(:,j),pixels/width,width)); drawnow; end end if strcmp(test,'CorrelogramFrame') | strcmp(test,'all') disp('CorrelogramFrame test'); for j=20:-1:1 c(j,:) = max(0,sin((1:256)/256*(21-j)*3*2*pi)); end picture=CorrelogramFrame(c,128,1,256); imagesc(picture) colormap(1-gray) end if strcmp(test,'CorrelogramMovie') | strcmp(test,'all') disp('CorrelogramMovie test'); u=MakeVowel(4000,FMPoints(4000,120),16000,'u'); soundsc(u,16000) coch=LyonPassiveEar(u,16000,1,4,.25); mov=CorrelogramMovie(coch,16000,16,256); movie(mov,-10,16) end if strcmp(test,'CorrelogramPitch') | strcmp(test,'all') disp('CorrelogramPitch test'); u=MakeVowel(20000,FMPoints(20000,120),22254,'u'); cor=CorrelogramArray(u,22254,50,256); p=CorrelogramPitch(cor,256,22254); plot(p) axis([0 45 110 130]); pause; coch=LyonPassiveEar(u,22254,1,4,.5); cor=CorrelogramArray(coch,22254,50,256); p=CorrelogramPitch(cor,256,22254); plot(p) axis([0 45 110 130]); pause; u=MakeVowel(20000,FMPoints(20000,120),22254,'u'); n=randn([1 20000]).*(1:20000)/20000; un=u+n/4; coch=LyonPassiveEar(un,22254,1,4,.5); cor=CorrelogramArray(coch,22254,50,256); [pitch sal]=CorrelogramPitch(cor,256,22254,100,200); plot(pitch); pause plot(sal); pause end if strcmp(test,'DesignLyonFilters') | strcmp(test,'all') disp('DesignLyonFilters test'); filts=DesignLyonFilters(16000); size(filts) filts(1:5,:) resp=soscascade([1 zeros(1,255)],filts); freqResp=20*log10(abs(fft(resp(1:5:88,:)'))); freqScale=(0:255)/256*16000; semilogx(freqScale(1:128),freqResp(1:128,:)) axis([100 10000 -60 20]); pause; end if strcmp(test,'EpsilonFromTauFS') | strcmp(test,'all') disp('EpsilonFromTauFS test'); eps=EpsilonFromTauFS(5,1) filter(1, [1 eps-1],[1 zeros(1,9)]) sosfilters([1 zeros(1,9)],[1 0 0 eps-1 0]) end if strcmp(test,'ERBSpace') | strcmp(test,'all') set_window_size(250, 150); disp('ERBSpace test') plot(ERBSpace) end if strcmp(test,'FMPoints') | strcmp(test,'all') disp('FMPoints test'); u=MakeVowel(20000,FMPoints(20000,120), 22050,'u'); soundsc(u/max(u), 22050) end if strcmp(test,'FreqResp') | strcmp(test,'all') disp('FreqResp test'); filts=DesignLyonFilters(16000); f=10:10:7990; resp=FreqResp(filts(2, :), f, 16000); semilogx(f,resp); axis([100 10000 -50 20]); end if strcmp(test,'LyonPassiveEar') | strcmp(test,'all') disp('LyonPassiveEar test'); is=LyonPassiveEar([1 zeros(1,255)],16000,1); imagesc(min(is, 0.0004)); pause s=sin((0:2041)/20000*2*pi*1000); ys=LyonPassiveEar(s,20000,20); imagesc(ys/max(max(ys))); pause; tap = wavread('tapestry.wav'); coch=LyonPassiveEar(tap,16000,100); imagesc(coch/max(max(coch))); pause; end if strcmp(test,'MakeERBFilters') | strcmp(test,'all') disp('MakeERBFilters test'); fcoefs = MakeERBFilters(16000,10,100); y = ERBFilterBank([1 zeros(1,511)], fcoefs); resp = 20*log10(abs(fft(y'))); freqScale = (0:511)/512*16000; semilogx(freqScale(1:255),resp(1:255,:)); axis([100 16000 -60 0]) xlabel('Frequency (Hz)'); ylabel('Filter Response (dB)'); pause; tap = wavread('tapestry.wav'); fcoefs=MakeERBFilters(16000,40,100); coch=ERBFilterBank(tap, fcoefs); for j=1:size(coch,1) c=max(coch(j,:),0); c=filter([1],[1 -.99],c); coch(j,:)=c; end imagesc(coch); end if strcmp(test,'MakeVowel') | strcmp(test,'all') disp('MakeVowel test'); vowels=[MakeVowel(10000,100,16000,'a') ... MakeVowel(10000,100,16000,'i') ... MakeVowel(10000,100,16000,'u')]; soundsc(vowels,16000); vowels=[MakeVowel(1000,100,16000,'a')... MakeVowel(1000,100,16000,'i') ... MakeVowel(1000,100,16000,'u')]; s=spectrogram(vowels,256,2,2); imagesc(s); pause end if strcmp(test,'MeddisHairCell') | strcmp(test,'all') disp('MeddisHairCell test'); tone=sin((0:4999)/20000*2*pi*1000); s=[zeros(1,5000) ... tone*10^(40/20-1.35) zeros(1,5000) ... tone*10^(45/20-1.35) zeros(1,5000) ... tone*10^(50/20-1.35) zeros(1,5000) ... tone*10^(55/20-1.35) zeros(1,5000) ... tone*10^(60/20-1.35) zeros(1,5000) ... tone*10^(65/20-1.35) zeros(1,5000) ... tone*10^(70/20-1.35) zeros(1,5000) ... tone*10^(75/20-1.35) zeros(1,5000) ... tone*10^(80/20-1.35)]; y=MeddisHairCell(s,20000); plot((1:90000)/20000,y(1:90000)); pause end if strcmp(test,'mfcc') | strcmp(test,'all') disp('mfcc test'); set_window_size(348, 188); tap = wavread('tapestry.wav'); [ceps,freqresp,fb,fbrecon,freqrecon] = mfcc(tap,16000,100); imagesc(ceps); colormap(1-gray); pause imagesc(flipud(freqresp)); pause imagesc(flipud(fb)); pause imagesc(flipud(fbrecon)); pause imagesc(flipud(freqrecon)); pause end if strcmp(test,'proclpc') | strcmp(test,'all') disp('proclpc test'); set_window_size(348, 188); [tap sr]= wavread('tapestry.wav'); lpc_spec(tap,sr,13); pause lpc_spec(tap,sr,26); pause end if strcmp(test,'rasta') | strcmp(test,'all') disp('rasta test'); tap = wavread('tapestry.wav'); [ceps,freqresp,fb,fbrecon,freqrecon] = mfcc(tap,16000,100); rastaout = rasta(ceps,100); mfccDCTMatrix = 1/sqrt(40/2)*cos((0:(13-1))' * ... (2*(0:(40-1))+1) * pi/2/40); mfccDCTMatrix(1,:) = mfccDCTMatrix(1,:)*sqrt(2)/2; rastarecon = 0*fbrecon; for i=1:size(rastaout,2) rastarecon(:,i) = mfccDCTMatrix' * rastaout(:,i); end imagesc(flipud(rastarecon)); end if strcmp(test,'SecondOrderFilter') | strcmp(test,'all') disp('SecondOrderFilter test'); f=10:10:7990; sos=SecondOrderFilter(3000,5,16000) filt=[1 0 0 sos(2:3)] semilogx(f,FreqResp(filt,f,16000)); pause filt=[sos 0 0] semilogx(f,FreqResp(filt,f,16000)); pause sos=SecondOrderFilter(3000,2,16000) filt=[sos 0 0] semilogx(f,FreqResp(filt,f,16000)); pause end if strcmp(test,'SeneffEar') | strcmp(test,'all') disp('SeneffEar test'); s=[zeros(1,160) sin(2000*2*pi/16000*(1:1120))]; y=SeneffEar(s,16000,15); pause; tap = wavread('tapestry.wav'); hc=SeneffEar(tap,16000); for j=1:40 c=hc(j,:); c=filter([1],[1, -.99],c); h(j,:)=c(1:100:50381); end clf; imagesc(h); pause; end if strcmp(test,'SetGain') | strcmp(test,'all') disp('SetGain test'); filts=DesignLyonFilters(16000); filt=filts(42,:) f=10:10:7990; semilogx(f,FreqResp(filt,f,16000)); pause; newFilt = SetGain(filt, 10, 1960, 16000); semilogx(f, FreqResp(newFilt, f, 16000)); pause end if strcmp(test,'soscascade') | strcmp(test,'all') disp('soscascade test'); soscascade([1 0 0 0 0],[1 0 0 -.9 0;1 1 0 0 0]) end if strcmp(test,'sosfilters') | strcmp(test,'all') disp('sosfilters test'); sosfilters([1 0 0 0 0 0],[1 0 0 -.9 0;1 0 0 -.8 0]) sosfilters([1 0 0 0 0 0;2 0 0 0 0 0], ... [1 0 0 -.9 0;1 0 0 -.8 0]) sosfilters([1 0 0 0 0 0;2 0 0 0 0 0],[1 0 0 -.9 0]) end if strcmp(test,'spectrogram') | strcmp(test,'all') disp('spectrogram test'); tap = wavread('tapestry.wav'); spec=spectrogram(tap,64,2,1); imagesc(spec); pause; end if strcmp(test,'synlpc') | strcmp(test,'all') disp('synlpc test'); [tap sr] = wavread('tapestry.wav'); [aCoeff,resid,pitch,G,parcor,stream] = proclpc(tap,sr,13); syntap = synlpc(aCoeff, stream, sr, G);; soundsc(syntap,16000); [aCoeff,resid,pitch,G,parcor,stream] = proclpc(tap,sr,13); stream=randn(size(stream)); syntap = synlpc(aCoeff, stream, sr, G);; soundsc(syntap,16000); end if strcmp(test,'WhiteVowel') | strcmp(test,'all') disp('WhiteVowel test'); [tap sr] = wavread('tapestry.wav'); whitetap = WhiteVowel(tap,16000,13,1000); soundsc(whitetap, 16000); end function lpc_spec(tap,sr,L) [aCoeff,resid,pitch,G,parcor,stream] = proclpc(tap,sr,L); cft=0:(1/255):1; spec = zeros(128, size(aCoeff,2)); for nframe=1:size(aCoeff,2) gain=20*log10(G(nframe)) * 0; for index=1:size(aCoeff,1) gain = gain + aCoeff(index,nframe)*exp(-i*2*pi*cft).^index; end gain = abs(1./gain); spec(:,nframe) = 20*log10(gain(1:128))'; end imagesc(flipud(spec)); function set_window_size(width, height) cursize = get(gcf, 'position'); cursize(3) = width+1; cursize(4) = height+1; set(gcf, 'position', cursize);
github
martinarielhartmann/mirtooloct-master
CorrelogramFrame.m
.m
mirtooloct-master/AuditoryToolbox/CorrelogramFrame.m
1,672
utf_8
f5b29d74df1508458ae5f23c6cfda1b8
% pic = CorrelogramFrame(data, picWidth, start, winLen) % Compute one frame of a correlogram. The input data is a % two-dimensional array of cochlear data, each row representing % firing probabilities from one cochlear channel. The output % picture is a two dimensional array of width "picWidth". % % The correlogram is computed with autocorrelation using % data from the input array. For each channel, the data from % is extracted starting at column "start" and extending for % "winLength" time steps. % (c) 1998 Interval Research Corporation function pic = CorrelogramFrame(data, picWidth, start, winLen) if nargin < 2 disp('Syntax: pic=CorrelogramFrame(data, picWidth[, start, len])'); return end if nargin < 3 start = 1; end if nargin < 4 [channels, winLen] = size(data); end [channels, dataLen] = size(data); start = max(1, start); last = min(dataLen, start+winLen-1); pic = zeros(channels, picWidth); fftSize = 2^(nextpow2(max(picWidth, winLen))+1); % disp(['CorrelogramFrame fftSize is ' int2str(fftSize)]); a = .54; b = -.46; wr = sqrt(64/256); phi = pi/winLen; ws = 2*wr/sqrt(4*a*a+2*b*b)*(a + b*cos(2*pi*(0:winLen-1)/winLen + phi)); for i=1:channels f = zeros(1, fftSize); % d = zeros(1, winLen); % d(1:(last-start+1)) = data(i,start:last) .* ws(1:(last-start+1)); % f(1:(winLen/2)) = d(winLen/2+1:winLen); % f(fftSize-(winLen/2)+1:fftSize) = d(1:min(length(d),winLen/2)); f(1:(last-start+1)) = data(i,start:last) .* ws(1:(last-start+1)); f = fft(f); f = ifft(f.*conj(f)); pic(i,:) = real(f(1:picWidth)); if pic(i,1) > pic(i,2) & pic(i,1) > pic(i,3) pic(i,:) = pic(i,:)/sqrt(pic(i,1)); else pic(i,:) = zeros(1,picWidth); end end
github
martinarielhartmann/mirtooloct-master
mfcc.m
.m
mirtooloct-master/AuditoryToolbox/mfcc.m
6,320
utf_8
e2a5640478ad49e3a283d3d1115bbf04
% mfcc - Mel frequency cepstrum coefficient analysis. % [ceps,freqresp,fb,fbrecon,freqrecon] = ... % mfcc(input, samplingRate, [frameRate]) % Find the cepstral coefficients (ceps) corresponding to the % input. Four other quantities are optionally returned that % represent: % the detailed fft magnitude (freqresp) used in MFCC calculation, % the mel-scale filter bank output (fb) % the filter bank output by inverting the cepstrals with a cosine % transform (fbrecon), % the smooth frequency response by interpolating the fb reconstruction % (freqrecon) % -- Malcolm Slaney, August 1993 % Modified a bit to make testing an algorithm easier... 4/15/94 % Fixed Cosine Transform (indices of cos() were swapped) - 5/26/95 % Added optional frameRate argument - 6/8/95 % Added proper filterbank reconstruction using inverse DCT - 10/27/95 % Added filterbank inversion to reconstruct spectrum - 11/1/95 % (c) 1998 Interval Research Corporation function [ceps,freqresp,fb,fbrecon,freqrecon] = ... mfcc(input, samplingRate, frameRate) global mfccDCTMatrix mfccFilterWeights [r c] = size(input); if (r > c) input=input'; end % Filter bank parameters lowestFrequency = 133.3333; linearFilters = 13; linearSpacing = 66.66666666; logFilters = 27; logSpacing = 1.0711703; fftSize = 512; cepstralCoefficients = 13; windowSize = 400; windowSize = 256; % Standard says 400, but 256 makes more sense % Really should be a function of the sample % rate (and the lowestFrequency) and the % frame rate. if (nargin < 2) samplingRate = 16000; end; if (nargin < 3) frameRate = 100; end; % Keep this around for later.... totalFilters = linearFilters + logFilters; % Now figure the band edges. Interesting frequencies are spaced % by linearSpacing for a while, then go logarithmic. First figure % all the interesting frequencies. Lower, center, and upper band % edges are all consequtive interesting frequencies. freqs = lowestFrequency + (0:linearFilters-1)*linearSpacing; freqs(linearFilters+1:totalFilters+2) = ... freqs(linearFilters) * logSpacing.^(1:logFilters+2); lower = freqs(1:totalFilters); center = freqs(2:totalFilters+1); upper = freqs(3:totalFilters+2); % We now want to combine FFT bins so that each filter has unit % weight, assuming a triangular weighting function. First figure % out the height of the triangle, then we can figure out each % frequencies contribution mfccFilterWeights = zeros(totalFilters,fftSize); triangleHeight = 2./(upper-lower); fftFreqs = (0:fftSize-1)/fftSize*samplingRate; for chan=1:totalFilters mfccFilterWeights(chan,:) = ... (fftFreqs > lower(chan) & fftFreqs <= center(chan)).* ... triangleHeight(chan).*(fftFreqs-lower(chan))/(center(chan)-lower(chan)) + ... (fftFreqs > center(chan) & fftFreqs < upper(chan)).* ... triangleHeight(chan).*(upper(chan)-fftFreqs)/(upper(chan)-center(chan)); end %semilogx(fftFreqs,mfccFilterWeights') %axis([lower(1) upper(totalFilters) 0 max(max(mfccFilterWeights))]) hamWindow = 0.54 - 0.46*cos(2*pi*(0:windowSize-1)/windowSize); if 0 % Window it like ComplexSpectrum windowStep = samplingRate/frameRate; a = .54; b = -.46; wr = sqrt(windowStep/windowSize); phi = pi/windowSize; hamWindow = 2*wr/sqrt(4*a*a+2*b*b)* ... (a + b*cos(2*pi*(0:windowSize-1)/windowSize + phi)); end % Figure out Discrete Cosine Transform. We want a matrix % dct(i,j) which is totalFilters x cepstralCoefficients in size. % The i,j component is given by % cos( i * (j+0.5)/totalFilters pi ) % where we have assumed that i and j start at 0. mfccDCTMatrix = 1/sqrt(totalFilters/2)*cos((0:(cepstralCoefficients-1))' * ... (2*(0:(totalFilters-1))+1) * pi/2/totalFilters); mfccDCTMatrix(1,:) = mfccDCTMatrix(1,:) * sqrt(2)/2; %imagesc(mfccDCTMatrix); % Filter the input with the preemphasis filter. Also figure how % many columns of data we will end up with. if 1 preEmphasized = filter([1 -.97], 1, input); else preEmphasized = input; end windowStep = samplingRate/frameRate; cols = fix((length(input)-windowSize)/windowStep); % Allocate all the space we need for the output arrays. ceps = zeros(cepstralCoefficients, cols); if (nargout > 1) freqresp = zeros(fftSize/2, cols); end; if (nargout > 2) fb = zeros(totalFilters, cols); end; % Invert the filter bank center frequencies. For each FFT bin % we want to know the exact position in the filter bank to find % the original frequency response. The next block of code finds the % integer and fractional sampling positions. if (nargout > 4) fr = (0:(fftSize/2-1))'/(fftSize/2)*samplingRate/2; j = 1; for i=1:(fftSize/2) if fr(i) > center(j+1) j = j + 1; end if j > totalFilters-1 j = totalFilters-1; end fr(i) = min(totalFilters-.0001, ... max(1,j + (fr(i)-center(j))/(center(j+1)-center(j)))); end fri = fix(fr); frac = fr - fri; freqrecon = zeros(fftSize/2, cols); end % Ok, now let's do the processing. For each chunk of data: % * Window the data with a hamming window, % * Shift it into FFT order, % * Find the magnitude of the fft, % * Convert the fft data into filter bank outputs, % * Find the log base 10, % * Find the cosine transform to reduce dimensionality. for start=0:cols-1 first = start*windowStep + 1; last = first + windowSize-1; fftData = zeros(1,fftSize); fftData(1:windowSize) = preEmphasized(first:last).*hamWindow; fftMag = abs(fft(fftData)); earMag = log10(mfccFilterWeights * fftMag'); ceps(:,start+1) = mfccDCTMatrix * earMag; if (nargout > 1) freqresp(:,start+1) = fftMag(1:fftSize/2)'; end; if (nargout > 2) fb(:,start+1) = earMag; end if (nargout > 3) fbrecon(:,start+1) = ... mfccDCTMatrix(1:cepstralCoefficients,:)' * ... ceps(:,start+1); end if (nargout > 4) f10 = 10.^fbrecon(:,start+1); freqrecon(:,start+1) = samplingRate/fftSize * ... (f10(fri).*(1-frac) + f10(fri+1).*frac); end end % OK, just to check things, let's also reconstruct the original FB % output. We do this by multiplying the cepstral data by the transpose % of the original DCT matrix. This all works because we were careful to % scale the DCT matrix so it was orthonormal. if 1 & (nargout > 3) fbrecon = mfccDCTMatrix(1:cepstralCoefficients,:)' * ceps; % imagesc(mt(:,1:cepstralCoefficients)*mfccDCTMatrix); end;
github
martinarielhartmann/mirtooloct-master
WhiteVowel.m
.m
mirtooloct-master/AuditoryToolbox/WhiteVowel.m
2,857
utf_8
0fc089b7af863423555a4e18c36ece15
function [output,aCoeff] = WhiteVowel(data,sr,L,pos) % function [output,aCoeff] = WhiteVowel(data,sr,L,pos) % % Speech is often described as having spectral peaks or formants which % identify the phonetic signal. An interesting experiment, first proposed by % XXX, filters a speech signal to remove all the formant information at one % time during the speech. If there are no formant peaks, how can the speech % be understood? It turns out that processing, much like RASTA, means that % relative changes in spectrum are the most important, thus the speech signal % is understood because the formant transitions carry the information. This % gives speech an important transparency due % % This function takes a speech signal (data) with a given sampling rate (sr). % It then finds the L-order LPC filter that describes the speech at the given % position (pos ms). The entire speech signal is then filtered with the % inverse of the LPC filter, effectively turning the speech spectrum at the % given time white (flat). % Chris Pal, Interval, May 1997 % (c) 1998 Interval Research Corporation fr = 20; fs = 30; preemp = .9378; % LPC defaults [row col] = size(data); if col==1 data=data'; end nframe = 0; msfr = round(sr/1000*fr); msfs = round(sr/1000*fs); duration = length(data); msoverlap = msfs - msfr; frameNumber = floor(pos/1000*sr/msfr); frameStart = round(pos/1000*sr - msfs/2); frameData = data(frameStart:(frameStart+msfs-1)); aCoeff = proclpc(frameData, sr, L, fr, fs, preemp); % Calculate the filter response % by evaluating the z-transform spec=lpc_spec(aCoeff); subplot(2,3,1); plot(spec); title('LPC Spectral Slice'); ylabel('Original') % Now do the actual whitening filter output = filter(aCoeff,1,data)'; frameData = output(frameStart:(frameStart+msfs-1)); bCoeff = proclpc(frameData, sr, L, fr, fs, preemp); spec=lpc_spec(bCoeff); subplot(2,3,4); plot(spec); ylabel('Whitened'); xlabel('FFT Bin'); % 256-DFT origSpec = 20*log10(abs(specgram(data,512,sr,msfs,msoverlap))); subplot(2,3,2),imagesc(origSpec); axis xy; colormap(1-gray); title('Spectrogram'); synSpec = 20*log10(abs(specgram(output,512,sr,msfs,msoverlap))); subplot(2,3,5),imagesc(synSpec); axis xy; colormap(1-gray); xlabel('Frame #'); origloc = origSpec(:,frameNumber); origloc=origloc-max(origloc);origmin=min(origloc); subplot(2,3,3),plot(origloc),title('Spectrogram'), axis([1 length(origloc) origmin 0]); filloc = synSpec(:,frameNumber); filloc=filloc-max(filloc); subplot(2,3,6),plot(filloc);ylabel('db'); axis([1 length(origloc) origmin 0]); xlabel('FFT Bin'); function spec=lpc_spec(aCoeff) gain=0; cft=0:(1/255):1; for index=1:size(aCoeff,1) gain = gain + aCoeff(index)*exp(-i*2*pi*cft).^index; end gain = abs(1./gain); spec = 20*log10(gain(1:128))';
github
martinarielhartmann/mirtooloct-master
DesignLyonFilters.m
.m
mirtooloct-master/AuditoryToolbox/DesignLyonFilters.m
3,715
utf_8
d1cdd19256fb6f4bf37de7636ad0f226
% [filters, freqs] = DesignLyonFilters(fs,EarQ,StepFactor) % Design the cascade of second order filters and the front filters % (outer/middle and compensator) needed for Lyon's Passive Short Wave % (Second Order Sections) cochlear model. The variables used here come % from Apple ATG Technical Report #13 titled "Lyon's Cochlear Model". % % Most of the parameters are hardwired into this m-function. The user % settable parameters are the digital sampling rate, the basic Q of the % each stage (usually 8 or 4), and the spacing factor between channels % (usually .25 and .125, respectively.) % % The result is returned as rows of second order filters; three coefficients % for the numerator and two for the denomiator. The coefficients are % [A0 A1 A2 B1 B2]..........................(Malcolm 1 Feb. 1993) % % (c) 1998 Interval Research Corporation function [filters, CenterFreqs, gains] = DesignLyonFilters(fs,EarQ,StepFactor) if nargin < 2 EarQ = 8; end if nargin < 3 StepFactor=EarQ/32; end Eb = 1000.0; EarZeroOffset = 1.5; EarSharpness = 5.0; EarPremphCorner = 300; % Find top frequency, allowing space for first cascade filter. topf = fs/2.0; topf = topf - (sqrt(topf^2+Eb^2)/EarQ*StepFactor*EarZeroOffset)+ ... sqrt(topf^2+Eb^2)/EarQ*StepFactor; % Find place where CascadePoleQ < .5 lowf = Eb/sqrt(4*EarQ^2-1); NumberOfChannels = floor((EarQ*(-log(lowf + sqrt(lowf^2 + Eb^2)) + ... log(topf + sqrt(Eb^2 + topf^2))))/StepFactor); % Now make an array of CenterFreqs..... This expression was derived by % Mathematica by integrating 1/EarBandwidth(cf) and solving for f as a % function of channel number. cn = 1:NumberOfChannels; CenterFreqs = (-((exp((cn*StepFactor)/EarQ)*Eb^2)/ ... (topf + sqrt(Eb^2 + topf^2))) + ... (topf + sqrt(Eb^2 + topf^2))./exp((cn*StepFactor)/EarQ))/2; % OK, now we can figure out the parameters of each stage filter. EarBandwidth = sqrt(CenterFreqs.^2+Eb^2)/EarQ; CascadeZeroCF = CenterFreqs + EarBandwidth * StepFactor * EarZeroOffset; CascadeZeroQ = EarSharpness*CascadeZeroCF./EarBandwidth; CascadePoleCF = CenterFreqs; CascadePoleQ = CenterFreqs./EarBandwidth; % Now lets find some filters.... first the zeros then the poles zerofilts = SecondOrderFilter(CascadeZeroCF, CascadeZeroQ, fs); polefilts = SecondOrderFilter(CascadePoleCF, CascadePoleQ, fs); filters = [zerofilts polefilts(:,2:3)]; % Now we can set the DC gain of each stage. dcgain(2:NumberOfChannels)=CenterFreqs(1:NumberOfChannels-1)./ ... CenterFreqs(2:NumberOfChannels); dcgain(1) = dcgain(2); for i=1:NumberOfChannels filters(i,:) = SetGain(filters(i,:), dcgain(i), 0, fs); end % Finally, let's design the front filters. front(1,:) = SetGain([0 1 -exp(-2*pi*EarPremphCorner/fs) 0 0], 1, fs/4, fs); topPoles = SecondOrderFilter(topf,CascadePoleQ(1), fs); front(2,:) = SetGain([1 0 -1 topPoles(2:3)], 1, fs/4, fs); % Now, put them all together. filters = [front; filters]; if nargout > 2 % Compute the gains needed so that everything is flat % when we do the filter inversion. [channels, width] = size(filters); len = length(CenterFreqs); clear cfs2; cfs2(1) = fs/2; cfs2(1:2:2*len) = CenterFreqs; cfs2(2:2:2*len-1) = (CenterFreqs(1:len-1) + CenterFreqs(2:len))/2; % cfs2 = CenterFreqs; resp = zeros(length(cfs2), channels); for i=1:channels resp(:,i) = FreqResp(filters(i,:), cfs2, fs)'; end % Each column vector of resp contains one channel's response % across all frequencies (in dB). cumresp = cumsum(resp')'; % cumresp now contains the total gain at output of i'th channel at % frequency f a=10.^(cumresp(:,3:channels)/20); a = a.* a; % Have to go through each filter twice. gains = [0; 0; a \ ones(length(cfs2),1)]; end
github
martinarielhartmann/mirtooloct-master
SeneffEarSetup.m
.m
mirtooloct-master/AuditoryToolbox/SeneffEarSetup.m
8,431
utf_8
c6d0292c56280a4d247f48c023187c6f
function [SeneffPreemphasis, SeneffFilterBank, SeneffForward, SeneffBackward] ... = SeneffEarSetup(fs) % This m-function is based on data from the following paper: % Benjamin D. Bryant and John D. Gowdy, "Simulation of Stages % I and II of Seneff's Auditory Model (SAM) Using Matlab", and % published in the Proceedings of the 1993 Matlab User's Group % Conference. % Thanks to Benjamin Bryant for supplying us with his filter % coefficients and the initial organization of this implementation. % (c) 1998 Interval Research Corporation % Set the following variable to a non-zero value to see a summary % of the filter bank's behaviour. plotTests = 0; % The following values were taken from Figure 2 of Bryant's paper. PreemphasisRTheta = [0.86 3.1148863;0.99 0; 0.5 0; 0.95 3.14159]; % The following values were taken from Table 1 of Bryant's paper. % They represent the cascade zeros (R-z and Theta-z), and the % second order poles (radius and theta) and zeros (radius and theta/2). % % R-z Theta-z Radius Theta R-z2 FilterBankRTheta = [ 0 3.14159 0.740055 2.633909 0.8 0.86 2.997077 0.753637 2.178169 0.8 0.86 2.879267 0.775569 1.856744 0.8 0.86 2.761458 0.798336 1.617919 0.8 0.86 2.643648 0.819169 1.433496 0.8 0.86 2.525839 0.837158 1.286795 0.8 0.8 2.964876 0.852598 1.167321 0.8 0.86 2.408029 0.865429 1.068141 0.8 0.86 2.29022 0.876208 0.984489 0.8 0.86 2.17241 0.885329 0.912985 0.8 0.86 2.054601 0.893116 0.851162 0.8 0.86 1.936791 0.899823 0.797179 0.8 0.8 2.788161 0.906118 0.749633 0.8 0.86 1.818981 0.911236 0.70744 0.8 0.86 1.701172 0.915747 0.669742 0.8 0.86 1.583362 0.919753 0.635858 0.8 0.86 1.465552 0.923335 0.605237 0.8 0.86 1.347743 0.926565 0.57743 0.8 0.8 2.611447 0.929914 0.552065 0.8 0.86 1.229933 0.932576 0.528834 0.8 0.86 1.112123 0.944589 0.487783 0.75 0.86 0.994314 0.957206 0.452645 0.660714 0.86 0.876504 0.956548 0.42223 0.672143 0.86 0.758694 0.956653 0.395644 0.682143 0.8 2.434732 0.956518 0.372208 0.690966 0.86 0.640885 0.956676 0.351393 0.69881 0.86 0.523075 0.956741 0.316044 0.712143 0.8 2.258018 0.956481 0.287157 0.723052 0.8 2.081304 0.956445 0.263108 0.732143 0.8 1.904589 0.956481 0.242776 0.739835 0.86 0.405265 0.958259 0.217558 0.749384 0.8 1.727875 0.963083 0.197086 0.757143 0.8 1.55116 0.969757 0.175115 0.769048 0.8 1.374446 0.97003 0.153697 0.780662 0.8 1.197732 0.970382 0.134026 0.791337 0.8 1.021017 0.970721 0.118819 0.799596 0.8 1.5 0.970985 0.106711 0.8 0.8 1.2 0.971222 0.096843 0.8 0.8 1 0.97144 0.088645 0.8 0.8 0.9 0.971645 0.081727 0.8]; % Let's plot the cascade zero locations and the locations of the % pole and zeros in the resonator. if plotTests clf; subplot(3,3,1); plot(FilterBankRTheta(:,1).*exp(i*FilterBankRTheta(:,2))) axis([-1 1 0 1]) title('Cascade Zero Locations') subplot(3,3,2); plot([FilterBankRTheta(:,3).*exp(i*FilterBankRTheta(:,4)) ... FilterBankRTheta(:,5).*exp(i*FilterBankRTheta(:,4)/2)],'+') title('Resonator Pole/Zero') drawnow; end % Convert r-theta form, first into a list of roots, then a polynomial roots=exp(i*PreemphasisRTheta(:,2)).*PreemphasisRTheta(:,1); SeneffPreemphasis=real(poly([roots;conj(roots)])); % Plot the preemphasis filter response, if desired if plotTests subplot(3,3,3); freqScale=(0:255)/256*8000; freqresp = FreqResp(SeneffPreemphasis,[1], freqScale, 16000); semilogx(freqScale,freqresp) title('Preemphasis Response'); axis([100 10000 -60 20]) drawnow; end % Now figure out the second order sections that make up the main % filter bank cascade. We put the zeros into the numerator (b's) % and there are no poles. Just to keep things simpler, we adjust % the gain of each filter to keep it unity gain at DC. [channels,width] = size(FilterBankRTheta); roots=exp(i*FilterBankRTheta(:,2)).*FilterBankRTheta(:,1); SeneffFilterBank = zeros(channels,5); for j=1:channels SeneffFilterBank(j,1:3) = poly([roots(j) conj(roots(j))]); SeneffFilterBank(j,1:3) = SeneffFilterBank(j,1:3)/sum(SeneffFilterBank(j,1:3)); end % Plot the cascade zero responses, if desired. if plotTests subplot(3,3,4); y=soscascade([1 zeros(1,511)],SeneffFilterBank); freqresp=20*log10(abs(fft(y(1:5:40,:)'))); freqScale=(0:511)/512*16000; semilogx(freqScale(1:256),freqresp(1:256,:)) axis([100 10000 -150 0]); title('Cascade Response'); drawnow; end % Now figure out the resonating filters. Each of these resonators % is a double pole-zero pair. zlocs = FilterBankRTheta(:,5).*exp(i*FilterBankRTheta(:,4)/2); plocs = FilterBankRTheta(:,3).*exp(i*FilterBankRTheta(:,4)); SeneffForward = zeros(5,channels); SeneffBackward = zeros(5,channels); for j=1:channels SeneffForward(:,j) = real(poly([zlocs(j) conj(zlocs(j)) ... zlocs(j) conj(zlocs(j))]))'; SeneffBackward(:,j) = real(poly([plocs(j) conj(plocs(j)) ... plocs(j) conj(plocs(j))]))'; end % Now plot the frequency response of just the resonating filters. % These are all bandpass filters. if plotTests subplot(3,3,5); impulse = [1 zeros(1,255)]; y=zeros(256,channels); for j=1:40 y(:,j) = filter(SeneffForward(:,j),SeneffBackward(:,j),impulse)'; end freqresp=20*log10(abs(fft(y(:,1:5:40)))); freqScale=(0:255)/256*16000; semilogx(freqScale(1:128),freqresp(1:128,:)) axis([100 10000 -30 40]); title('Resonators Response') drawnow; end % The plot below shows the overall response of the preemphasis filters % along with the just-designed cascade of zeros. if plotTests subplot(3,3,6); impulse = [1 zeros(1,511)]; y=soscascade(filter(SeneffPreemphasis, [1], impulse), ... SeneffFilterBank); freqresp=20*log10(abs(fft(y(1:5:40,:)'))); freqScale=(0:511)/512*16000; semilogx(freqScale(1:256),freqresp(1:256,:)) axis([100 10000 -100 25]); title('Preemphasis+Cascade'); drawnow; end % Now we need to normalize the gain of each channel. We run an impulse % through the preemphasis filter, and then through the cascade of zeros. % Finally, we run it through each of the resonator filters. impulse = [1 zeros(1,255)]; y=soscascade(filter(SeneffPreemphasis, [1], impulse), ... SeneffFilterBank); for j=1:channels y(j,:) = filter(SeneffForward(:,j),SeneffBackward(:,j),y(j,:)); end % Now we have impulse responses from each filter. We can find the FFT % and then find the gain peak. We divide each forward polynomial by the % maximum gain (to normalize) and then multiply by the desired low % frequency roll-off. The Bryant paper says that the last 24 channels % should be cut at 6dB per octave and that this occurs at 1600 Hz, but % it looks to me like the gain change happens at 3200 Hz. freqresp=abs(fft(y')); gain = ones(1,channels)./max(freqresp); cfs = FilterBankRTheta(:,4)/pi*fs/2; rolloff = min(cfs/1600,1); for j=1:channels SeneffForward(:,j)=SeneffForward(:,j)*gain(j)*rolloff(j); end % All Done. The figure below should match Figure 3 of Bryant's paper. if plotTests subplot(3,3,8); impulse = [1 zeros(1,511)]; y=soscascade(filter(SeneffPreemphasis, [1], impulse), ... SeneffFilterBank); for j=1:channels y(j,:) = filter(SeneffForward(:,j),SeneffBackward(:,j),y(j,:)); end freqresp=20*log10(abs(fft(y(1:5:40,:)'))); freqScale=(0:511)/512*16000; plot(freqScale(1:256),freqresp(1:256,:)) axis([100 10000 -120 0]); title('Magnitude Response vs. Linear Frequency'); drawnow; end function mag=FreqResp(b,a,f,fs) cf = exp(i*2*pi*f/fs); num = 0; for i=1:length(b) num = num + b(end-i+1)*cf.^i; end denom = 0; for i=1:length(a) denom = denom + a(end-i+1)*cf.^i; end mag = 20*log10(abs(num./denom));
github
martinarielhartmann/mirtooloct-master
mirdecreaseslope.m
.m
mirtooloct-master/MIRToolbox/mirdecreaseslope.m
3,058
utf_8
920edc53acc219af8f32e695e16db0c3
function varargout = mirdecreaseslope(orig,varargin) % a = mirattackslope(x) estimates the average slope of each note attack. % Values are expressed in the same scale than the original signal, % but normalised by time in seconds. % Optional arguments: % a = mirattackslope(x,m) specifies a method for slope computation. % Possible values: % m = 'Diff': ratio between the magnitude difference at the % beginning and the ending of the attack period, and the % corresponding time difference. % m = 'Gauss': average of the slope, weighted by a gaussian % curve that emphasizes values at the middle of the attack % period. (similar to Peeters 2004). % mirattackslope(...,'Contrast',c) specifies the 'Contrast' parameter % used in mironsets for event detection through peak picking. % Same default value as in mironsets. % mirattackslope(...,'Single') only selects one attack phase in the % signal (or in each segment). % % Peeters. G. (2004). A large set of audio features for sound description % (similarity and classification) in the CUIDADO project. version 1.0 meth.type = 'String'; meth.choice = {'Diff','Gauss'}; meth.default = 'Diff'; option.meth = meth; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = NaN; option.cthr = cthr; single.key = 'Single'; single.type = 'Boolean'; single.default = 0; option.single = single; log.key = 'LogOnset'; log.type = 'Boolean'; log.default = 0; option.log = log; minlog.key = 'MinLog'; minlog.type = 'Integer'; minlog.default = 0; option.minlog = minlog; specif.option = option; varargout = mirfunction(@mirdecreaseslope,orig,varargin,nargout,specif,@init,@main); function [o type] = init(x,option) o = mironsets(x,'Release','Contrast',option.cthr,'Single',option.single,... 'Log',option.log,'MinLog',option.minlog,... 'Filter','Normal','AcrossSegments'); type = mirtype(x); function sl = main(o,option,postoption) if iscell(o) o = o{1}; end pr = get(o,'ReleasePos'); pru = get(o,'ReleasePosUnit'); sr = get(o,'Sampling'); d = get(o,'Data'); sl = mircompute(@algo,pr,pru,d,option.meth,sr); fp = mircompute(@frampose,pru); sl = mirscalar(o,'Data',sl,'FramePos',fp,'Title','Decrease Slope'); sl = {sl,o}; function fp = frampose(pr) if isempty(pr) fp = []; return end pr = pr{1}; fp = pr; function sl = algo(pr,pru,d,meth,sr) if isempty(pr) sl = []; return end pr = pr{1}; pru = pru{1}; sl = zeros(1,length(pr)); for i = 1:size(pr,2) switch meth case 'Diff' sl(i) = (d(pr(1,i))-d(pr(2,i)))/(pru(2,i)-pru(1,i)); case 'Gauss' l = pr(2,i)-pr(1,i); h = ceil(l/2); gauss = exp(-(1-h:l-h).^2/(l/4)^2); dat = -diff(d(pr(1,i):pr(2,i))).*gauss'; sl(i) = mean(dat)*sr; end end
github
martinarielhartmann/mirtooloct-master
mirattackslope.m
.m
mirtooloct-master/MIRToolbox/mirattackslope.m
3,344
utf_8
c1ae3e613ee78509e576de00df491848
function varargout = mirattackslope(orig,varargin) % a = mirattackslope(x) estimates the average slope of each note attack. % Values are expressed in the same scale than the original signal, % but normalised by time in seconds. % Optional arguments: % a = mirattackslope(x,m) specifies a method for slope computation. % Possible values: % m = 'Diff': ratio between the magnitude difference at the % beginning and the ending of the attack period, and the % corresponding time difference. % m = 'Gauss': average of the slope, weighted by a gaussian % curve that emphasizes values at the middle of the attack % period. (similar to Peeters 2004). % mirattackslope(...,'Contrast',c) specifies the 'Contrast' parameter % used in mironsets for event detection through peak picking. % Same default value as in mironsets. % mirattackslope(...,'Single') only selects one attack phase in the % signal (or in each segment). % % Peeters. G. (2004). A large set of audio features for sound description % (similarity and classification) in the CUIDADO project. version 1.0 meth.type = 'String'; meth.choice = {'Diff','Gauss'}; meth.default = 'Diff'; option.meth = meth; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = NaN; option.cthr = cthr; single.key = 'Single'; single.type = 'Boolean'; single.default = 0; option.single = single; log.key = 'LogOnset'; log.type = 'Boolean'; log.default = 0; option.log = log; minlog.key = 'MinLog'; minlog.type = 'Integer'; minlog.default = 0; option.minlog = minlog; envmeth.type = 'String'; envmeth.choice = {'Filter','Spectro'}; envmeth.default = 'Filter'; option.envmeth = envmeth; specif.option = option; varargout = mirfunction(@mirattackslope,orig,varargin,nargout,specif,@init,@main); function [o type] = init(x,option) o = mironsets(x,'Attack','Contrast',option.cthr,'Single',option.single,... 'Log',option.log,'MinLog',option.minlog,... option.envmeth,'Normal','AcrossSegments'); type = mirtype(x); function sl = main(o,option,postoption) if iscell(o) o = o{1}; end po = get(o,'PeakPos'); pa = get(o,'AttackPos'); pou = get(o,'PeakPosUnit'); pau = get(o,'AttackPosUnit'); sr = get(o,'Sampling'); d = get(o,'Data'); sl = mircompute(@algo,po,pa,pou,pau,d,option.meth,sr); fp = mircompute(@frampose,pau,pou); sl = mirscalar(o,'Data',sl,'FramePos',fp,'Title','Attack Slope'); sl = {sl,o}; function fp = frampose(pa,po) if isempty(pa) fp = []; return end pa = sort(pa{1}); po = sort(po{1}); fp = [pa(:)';po(:)']; function sl = algo(po,pa,pou,pau,d,meth,sr) if isempty(pa) sl = []; return end pa = sort(pa{1}); po = sort(po{1}); pau = sort(pau{1}); pou = sort(pou{1}); sl = zeros(1,length(pa)); for i = 1:length(pa) switch meth case 'Diff' sl(i) = (d(po(i))-d(pa(i)))/(pou(i)-pau(i)); case 'Gauss' l = po(i)-pa(i); h = ceil(l/2); gauss = exp(-(1-h:l-h).^2/(l/4)^2); dat = diff(d(pa(i):po(i))).*gauss'; sl(i) = mean(dat)*sr; end end
github
martinarielhartmann/mirtooloct-master
mirinharmonicity.m
.m
mirtooloct-master/MIRToolbox/mirinharmonicity.m
4,045
utf_8
0694141a4a821cbd7da88eb33ab9691d
function varargout = mirinharmonicity(orig,varargin) % ih = mirinharmonicity(x) estimates the inharmonicity of x, i.e., the % amount of partials that are not multiples of the fundamental % frequency. % x can be either an audio file, a miraudio or a mirspectrum object. % WARNING: This function presupposes that there is only one fundamental % frequency. % Optional argument: % mirinharmonicity(...,'f0',f) bases the computation of the % inharmonicity on the fundamental frequency indicated by f. % Default value: f = mirpitch(...,'Mono') % [ih,s] = mirinharmonicity(x) also displays the spectrum used for the % computation of the inharmonicity. % [ih,s,p] = mirinharmonicity(x) also displays the result of the % estimation of the fundamental frequency. f0.key = 'f0'; f0.default = []; option.f0 = f0; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [.1 .125]; option.frame = frame; specif.option = option; varargout = mirfunction(@mirinharmonicity,orig,varargin,nargout,specif,@init,@main); function [i type] = init(x,option) if isamir(x,'miraudio') if option.frame.length.val s = mirspectrum(x,'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend); else s = mirspectrum(x); end else s = x; end if isempty(option.f0) if option.frame.length.val p = mirpitch(x,'Mono','Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend); else p = mirpitch(x,'Mono'); end else p = option.f0; end i = {s,p}; type = {'mirscalar','mirspectrum','mirscalar'}; function ih = main(x,option,postoption) if isa(x{2},'mirdesign') x = x{1}; end s = x{1}; p = x{2}; if iscell(p) p = p{1}; end m = get(s,'Magnitude'); f = get(s,'Frequency'); fp1 = get(s,'FramePos'); if isnumeric(p) pf = {{{p}}}; else pf = get(p,'Data'); fp2 = get(p,'FramePos'); end v = cell(1,length(m)); for h = 1:length(m) v{h} = cell(1,length(m{h})); for i = 1:length(m{h}) mi = m{h}{i}; fi = f{h}{i}; pfi = pf{h}{i}; v{h}{i} = zeros(1,size(mi,2),size(mi,3)); if not(size(mi,2) == size(pfi,2)) beg = find(fp2{h}{i}(1,:) == fp1{h}{i}(1,1)); if isempty(beg) || (beg + size(mi,2)-1 > size(pfi,2)) error('ERROR IN MIRINHARMONICITY: The ''f0'' argument should have the same frame decomposition than the main input.'); end pfi = pfi(:,beg:beg+size(mi,2)-1); end for j = 1:size(mi,3) for k = 1:size(mi,2) mk = mi(:,k,j); fk = fi(:,k,j); pfk = pfi(:,k); if isempty(pfk{1}) v{h}{i}(1,k,j) = NaN; else r = fk/pfk{1}(1); rr = 2*abs(r-round(r)); if isempty(rr) v{h}{i}(1,k,j) = NaN; else v{h}{i}(1,k,j) = sum(rr.*mk) / sum(mk); end end end end end end ih = mirscalar(s,'Data',v,'Title','Inharmonicity'); if isa(p,'mirdata') ih = {ih s p}; else ih = {ih s}; end
github
martinarielhartmann/mirtooloct-master
mirplay.m
.m
mirtooloct-master/MIRToolbox/mirplay.m
7,791
utf_8
c1b6dfd6436bb3a647097f575c478056
function varargout = mirplay(a,varargin) % mirplay(a) plays audio signal, envelope, or pitches. % If a is an envelope, what is actually played is a white noise of % same envelope. % If a is a mirpitch object, pitches are played using sinusoids. % Optional arguments: % mirplay(...,'Channel',i) plays the channel(s) of rank(s) indicated by % the array i. % mirplay(...,'Segment',k) plays the segment(s) of rank(s) indicated by % the array k. % mirplay(...,'Sequence',l) plays the sequence(s) of rank(s) indicated % by the array l. % mirplay(...,'Increasing',d) plays the sequences in increasing order % of d, which could be either an array or a mirscalar data. % mirplay(...,'Decreasing',d) plays the sequences in decreasing order % of d, which could be either an array or a mirscalar data. % mirplay(...,'Every',s) plays every s sequence, where s is a number % indicating the step between sequences. % mirplay(...,'Burst',0) toggles off the burst sound between % segments. % Example: mirplay(mirenvelope('Folder'),... % 'increasing', mirrms('Folder'),... % 'every',5) ch.key = 'Channel'; ch.type = 'Integer'; ch.default = 0; option.ch = ch; sg.key = 'Segment'; sg.type = 'Integer'; sg.default = 0; option.sg = sg; se.key = 'Sequence'; se.type = 'Integer'; se.default = 0; option.se = se; inc.key = 'Increasing'; inc.type = 'MIRtb'; option.inc = inc; dec.key = 'Decreasing'; dec.type = 'MIRtb'; option.dec = dec; every.key = 'Every'; every.type = 'Integer'; option.every = every; burst.key = 'Burst'; burst.type = 'Boolean'; burst.default = 0; %1; option.burst = burst; specif.option = option; specif.eachchunk = 'Normal'; varargout = mirfunction(@mirplay,a,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = ''; function noargout = main(a,option,postoption) if iscell(a) a = a{1}; end d = get(a,'Data'); if isa(a,'mirpitch') amp = get(a,'Amplitude'); end f = get(a,'Sampling'); n = get(a,'Name'); c = get(a,'Channels'); fp = get(a,'FramePos'); t = get(a,'Title'); if not(option.se) if length(d)>1 if isfield(option,'inc') [unused order] = sort(mirgetdata(option.inc)); elseif isfield(option,'dec') [unused order] = sort(mirgetdata(option.dec),'descend'); else order = 1:length(d); end if isfield(option,'every') order = order(1:option.every:end); end else order = 1; end else order = option.se; end if not(isempty(order)) for k = order(:)' if isamir(a,'miraudio') display(['Playing file: ' n{k}]) else display(['Playing ',t,' related to file: ' n{k}]) end dk = d{k}; if not(iscell(dk)) dk = {dk}; end if option.ch if isempty(c{k}) chk = option.ch; else [unused unused chk] = intersect(option.ch,c{k}); end else chk = 1:size(dk{1},3); end if isempty(chk) display('No channel to play.'); end for l = chk if chk(end)>1 display([' Playing channel #' num2str(l)]); end if option.sg sgk = option.sg(find(option.sg<=length(dk))); else sgk = 1:length(dk); end for i = sgk if sgk(end)>1 display([' Playing segment #' num2str(i)]) end di = dk{i}; if isa(a,'miraudio') for j = 1:size(di,2) tic pl = audioplayer(di(:,j,l),f{k}); playblocking(pl); % We should scale, in order to avoid clipping % (when reading AIF files for instance). % But global scaling across segments, to avoid % problem with silent segments. idealtime = size(di,1)/f{k}; practime = toc; if practime < idealtime pause(idealtime-practime) end end else synth = zeros(1,ceil((fp{k}{i}(end)-fp{k}{i}(1))*44100)+1); if isa(a,'mirpitch') stp = get(a,'Start'); transcribed = ~(isempty(stp) || isempty(stp{k}) ... || isempty(stp{k}{i})); else transcribed = 0; end if transcribed stp = get(a,'Start'); enp = get(a,'End'); mep = get(a,'Mean'); stp = stp{k}{i}{1}; enp = enp{k}{i}{1}; mep = mep{k}{i}{1}; for j = 1:length(mep) fj = 2^(mep(j)/1200); k1 = floor((fp{k}{i}(1,stp(j))-fp{k}{i}(1))*44100)+1; k2 = floor((fp{k}{i}(2,enp(j))-fp{k}{i}(1))*44100)+1; ampj = ones(1,k2-k1+1); synth(k1:k2) = synth(k1:k2) ... + sum(ampj.*sin(2*pi*fj*(0:k2-k1)/44100),1) ... .*hann(k2-k1+1)'; end else if isa(a,'mirpitch') ampi = amp{k}{i}; end for j = 1:size(di,2) if iscell(di) dj = di{j}; else dj = di(:,j); end dj(isnan(dj)) = 0; if isa(a,'mirpitch') ampj = zeros(size(dj)); if iscell(ampi) ampj(1:size(ampi{j})) = ampi{j}; else ampj(1:size(ampi(:,j))) = ampi(:,j); end end if not(isempty(dj)) k1 = floor((fp{k}{i}(1,j)-fp{k}{i}(1))*44100)+1; k2 = floor((fp{k}{i}(2,j)-fp{k}{i}(1))*44100)+1; if isa(a,'mirpitch') ampj = repmat(ampj,1,k2-k1+1); else ampj = ones(size(dj),k2-k1+1); end synth(k1:k2) = synth(k1:k2) ... + sum(ampj.*sin(2*pi*dj*(0:k2-k1)/44100),1) ... .*hann(k2-k1+1)'; end end end pl = audioplayer(synth,44100); playblocking(pl); end if option.burst && sgk(end)>1 pl = audioplayer(rand(1,10),8192); playblocking(pl); end end end end end noargout = {};
github
martinarielhartmann/mirtooloct-master
mirpeaks.m
.m
mirtooloct-master/MIRToolbox/mirpeaks.m
59,750
utf_8
4a36bc7f0d4dad5116030909c0f65dca
function varargout = mirpeaks(orig,varargin) % p = mirpeaks(x) detect peaks in x. % Optional argument: % mirpeaks(...,'Total',m): only the m highest peaks are selected. % If m=Inf, no limitation of number of peaks. % Default value: m = Inf % mirpeaks(...,'Order',o): specifies the ordering of the peaks. % Possible values for o: % 'Amplitude': orders the peaks from highest to lowest % (Default choice.) % 'Abscissa': orders the peaks along the abscissa axis. % mirpeaks(...,'Contrast',cthr): a threshold value. A given local % maximum will be considered as a peak if the difference of % amplitude with respect to both the previous and successive % local minima (when they exist) is higher than the threshold % cthr. This distance is expressed with respect to the % total amplitude of x: a distance of 1, for instance, is % equivalent to the distance between the maximum and the minimum % of x. % Default value: cthr = 0.1 % mirpeaks(...,'SelectFirst',fthr): If the 'Contrast' selection has % been chosen, this additional option specifies that when one % peak has to be chosen out of two candidates, and if the % difference of their amplitude is below the threshold fthr, % then the most ancien one is selected. % Option toggled off by default: % Default value if toggled on: fthr = cthr/2 % mirpeaks(...,'Threshold',thr): a threshold value. % A given local maximum will be considered as a peak if its % normalized amplitude is higher than this threshold. % A given local minimum will be considered as a valley if its % normalized amplitude is lower than this threshold. % The normalized amplitude can have value between 0 (the minimum % of the signal in each frame) and 1 (the maximum in each % frame). % Default value: thr=0 for peaks thr = 1 for valleys % mirpeaks(...,'Interpol',i): estimates more precisely the peak % position and amplitude using interpolation. Performed only on % data with numerical abscissae axis. % Possible value for i: % '', 'no', 'off', 0: no interpolation % 'Quadratic': quadratic interpolation. (default value). % mirpeaks(...,'Valleys'): detect valleys instead of peaks. % mirpeaks(...,'Reso',r): removes peaks whose abscissa distance to % one or several higher peaks is lower than a given threshold. % Possible value for the threshold r: % 'SemiTone': ratio between the two peak positions equal to % 2^(1/12) % a numerical value : difference between the two peak % positions equal to that value % When two peaks are distant by an interval lower than the % resolution, the highest of them is selected by default. % mirpeaks(...,'Reso',r,'First') specifies on the contrary that % the first of them is selected by default. % When a peak p1 is too close to another higher peak p2, p1 is % removed even if p2 is removed as well. If you want to % filter out p1 only if p2 remains in the end, add the option % 'Loose'. % mirpeaks(...,'Reso',r,'Loose') specifies instead that % mirpeaks(...,'Nearest',t,s): takes the peak nearest a given abscisse % values t. The distance is computed either on a linear scale % (s = 'Lin') or logarithmic scale (s = 'Log'). In this case, % only one peak is extracted. % mirpeaks(...,'Pref',c,std): indicates a region of preference for % the peak picking, centered on the abscisse value c, with a % standard deviation of std. % mirpeaks(...,'NoBegin'): does not consider the first sample as a % possible peak candidate. % mirpeaks(...,'NoEnd'): does not consider the last sample as a possible % peak candidate. % mirpeaks(...,'Normalize',n): specifies whether frames are % normalized globally or individually. % Possible value for n: % 'Global': normalizes the whole frames altogether from 0 to % 1 (default choice). % 'Local': normalizes each frame from 0 to 1. % mirpeaks(...,'Extract'): extracts from the initial curves all the % positive continuous segments (or "curve portions") where peaks % are located. % mirpeaks(...,'Only'): keeps from the original curve only the data % corresponding to the peaks, and zeroes the remaining data. % mirpeaks(...,'Track',t): tracks temporal continuities of peaks. If % a value t is specified, the variation between successive peaks % is tolerated up to t samples. % mirpeaks(...,'CollapseTrack',ct): collapses tracks into one single % track, and remove small track transitions, of length shorter % than ct samples. Default value: ct = 7 m.key = 'Total'; m.type = 'Integer'; m.default = Inf; option.m = m; nobegin.key = 'NoBegin'; nobegin.type = 'Boolean'; nobegin.default = 0; option.nobegin = nobegin; noend.key = 'NoEnd'; noend.type = 'Boolean'; noend.default = 0; option.noend = noend; order.key = 'Order'; order.type = 'String'; order.choice = {'Amplitude','Abscissa'}; order.default = 'Amplitude'; option.order = order; chro.key = 'Chrono'; % obsolete, corresponds to 'Order','Abscissa' chro.type = 'Boolean'; chro.default = 0; option.chro = chro; ranked.key = 'Ranked'; % obsolete, corresponds to 'Order','Amplitude' ranked.type = 'Boolean'; ranked.default = 0; option.ranked = ranked; vall.key = 'Valleys'; vall.type = 'Boolean'; vall.default = 0; option.vall = vall; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = .1; option.cthr = cthr; first.key = 'SelectFirst'; first.type = 'Integer'; first.default = 0; first.keydefault = NaN; option.first = first; thr.key = 'Threshold'; thr.type = 'Integer'; thr.default = NaN; option.thr = thr; smthr.key = 'MatrixThreshold'; % to be documented in version 1.3 smthr.type = 'Integer'; smthr.default = NaN; option.smthr = smthr; graph.key = 'Graph'; graph.type = 'Integer'; graph.default = 0; graph.keydefault = 1; %.25; option.graph = graph; interpol.key = 'Interpol'; interpol.type = 'String'; interpol.default = 'Quadratic'; interpol.keydefault = 'Quadratic'; option.interpol = interpol; reso.key = 'Reso'; %reso.type = 'String'; %reso.choice = {0,'SemiTone'}; reso.default = 0; option.reso = reso; resofirst.key = 'First'; resofirst.type = 'Boolean'; resofirst.default = 0; option.resofirst = resofirst; resoloose.key = 'Loose'; resoloose.type = 'Boolean'; resoloose.default = 0; option.resoloose = resoloose; c.key = 'Pref'; c.type = 'Integer'; c.number = 2; c.default = [0 0]; option.c = c; near.key = 'Nearest'; near.type = 'Integer'; near.default = NaN; option.near = near; logsc.type = 'String'; logsc.choice = {'Lin','Log',0}; logsc.default = 'Lin'; option.logsc = logsc; normal.key = 'Normalize'; normal.type = 'String'; normal.choice = {'Local','Global'}; normal.default = 'Global'; option.normal = normal; extract.key = 'Extract'; extract.type = 'Boolean'; extract.default = 0; option.extract = extract; only.key = 'Only'; only.type = 'Boolean'; only.default = 0; option.only = only; delta.key = 'Track'; delta.type = 'Integer'; delta.default = 0; delta.keydefault = Inf; option.delta = delta; harmo.key = 'Harmonic'; harmo.type = 'Integer'; harmo.default = 0; harmo.keydefault = Inf; option.harmo = harmo; mem.key = 'TrackMem'; mem.type = 'Integer'; mem.default = 0; mem.keydefault = Inf; option.mem = mem; fuse.key = 'Fuse'; fuse.type = 'Boolean'; fuse.default = 0; option.fuse = fuse; shorttrackthresh.key = 'CollapseTracks'; shorttrackthresh.type = 'Integer'; shorttrackthresh.default = 0; shorttrackthresh.keydefault = 7; option.shorttrackthresh = shorttrackthresh; scan.key = 'ScanForward'; % specific to mironsets(..., 'Klapuri99') scan.default = []; option.scan = scan; specif.option = option; varargout = mirfunction(@mirpeaks,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = mirtype(x); function p = main(x,option,postoption) if iscell(x) x = x{1}; end if option.chro option.order = 'Abscissa'; elseif option.ranked option.order = 'Amplitude'; end if not(isnan(option.near)) && option.m == 1 option.m = Inf; end x = purgedata(x); if option.m <= 0 p = x; return end d = get(x,'Data'); sr = get(x,'Sampling'); cha = 0; % Indicates when it is possible to represent as a curve along the % Z-axis (channels) instead of the X-axis (initial abscissa). if isnan(option.first) option.first = option.cthr / 2; end if isa(x,'mirscalar') t = get(x,'FramePos'); for i = 1:length(d) for j = 1:length(d{i}) d{i}{j} = d{i}{j}'; if size(t{i},1) == 1 t{i}{j} = t{i}{j}(1,:,:)'; else t{i}{j} = (t{i}{j}(1,:,:)+t{i}{j}(2,:,:))'/2; end end end elseif isa(x,'mirsimatrix') t = get(x,'FramePos'); for i = 1:length(t) for j = 1:length(t{i}) t{i}{j} = repmat((t{i}{j}(1,:,:)+t{i}{j}(2,:,:))'/2,... [1 size(d{i}{j},2) 1]); end end elseif isa(x,'mirhisto') error('ERROR IN MIRPEAKS: peaks of histogram not considered yet.'); else for i = 1:length(d) for j = 1:length(d{i}) if iscell(d{i}) dij = d{i}{j}; if ~cha && j == 1 && size(dij,3) > 1 && size(dij,1) == 1 cha = 1; end if cha && j > 1 && size(dij,1) > 1 cha = -1; end end end for j = 1:length(d{i}) if iscell(d{i}) dij = d{i}{j}; if cha == 1 if iscell(dij) for k = 1:size(dij,2) d{i}{j}{k} = reshape(dij{k},size(dij{k},2),size(dij{k},3)); d{i}{j}{k} = d{i}{j}{k}'; end else d{i}{j} = reshape(dij,size(dij,2),size(dij,3)); d{i}{j} = d{i}{j}'; end end end end end if cha == 1 t = get(x,'Channels'); else t = get(x,'Pos'); end end interpol = get(x,'Interpolable') && not(isempty(option.interpol)) && ... ((isnumeric(option.interpol) && option.interpol) || ... (ischar(option.interpol) && not(strcmpi(option.interpol,'No')) && ... not(strcmpi(option.interpol,'Off')))); pp = cell(1,length(d)); pv = cell(1,length(d)); pm = cell(1,length(d)); ppp = cell(1,length(d)); ppv = cell(1,length(d)); tp = cell(1,length(d)); if interpol tpp = cell(1,length(d)); tpv = cell(1,length(d)); end tv = cell(1,length(d)); if isnan(option.thr) option.thr = 0; else if option.vall option.thr = 1-option.thr; end end %if isnan(option.lthr) % option.lthr = 1; %else % if option.vall % option.lthr = 1-option.lthr; % end %end if isnan(option.smthr) option.smthr = option.thr - .2; end if not(isempty(option.scan)) pscan = get(option.scan,'PeakPos'); end for i = 1:length(d) % For each audio file,... di = d{i}; if cha == 1 ti = t; %sure ? else ti = t{i}; end if not(iscell(di)) di = {di}; if isa(x,'mirchromagram') && not(cha) ti = {ti}; end end if option.vall for h = 1:length(di) di{h} = -di{h}; end end if strcmpi(option.normal,'Global') % Normalizing across segments madi = zeros(1,length(di)); midi = zeros(1,length(di)); for h = 1:length(di) madi(h) = max(max(max(max(di{h},[],1),[],2),[],3),[],4); midi(h) = min(min(min(min(di{h},[],1),[],2),[],3),[],4); end mad = max(madi); mid = min(midi); end for h = 1:length(di) % For each segment,... dhu = di{h}; % This copy of the data is kept untransformed and used for output. dht = dhu; % This copy of the data will be transformed (normalization, etc.) [nl0 nc np nd0] = size(dhu); if cha == 1 if iscell(ti) %% problem here!!! ti = ti{i}; %%%%%it seems that sometimes we need to use instead ti{i}(:); end th = repmat(ti,[1,nc,np,nd0]); else th = ti{h}; if iscell(th) % Non-numerical abscissae are transformed into numerical ones. th = repmat((1:size(th,1))',[1,nc,np]); else if 0 %size(th,2) == 1 && nc>1 error('Problematic case. New code below to be used.'); th = repmat(th,[1,nc,1]); end if size(th,3)<np th = repmat(th,[1,1,np]); end end end if strcmpi(option.normal,'Global') % Normalizing across segments dht = (dht - repmat(mid,[nl0 nc np nd0]))./... repmat(mad-mid,[nl0 nc np nd0]); end if option.c % If a prefered region is specified, the data is amplified accordingly dht = dht.*exp(-(th-option.c(1)).^2/2/option.c(2)^2)... /option.c(2)/sqrt(2*pi)/2; end % Now the data is rescaled. the minimum is set to 0 % and the maximum to 1. state = warning('query','MATLAB:divideByZero'); warning('off','MATLAB:divideByZero'); for l = 1:nd0 [unused lowc] = find(max(dht(:,:,:,l))<option.thr); dht(:,lowc,1,l) = 0; end if strcmpi(option.normal,'Local') % Normalizing each frame separately: dht = (dht-repmat(min(min(dht,[],1),[],4),[nl0 1 1 nd0]))./... repmat(max(max(dht,[],1),[],4)... -min(min(dht,[],1),[],4),[nl0 1 1 nd0]); end warning(state.state,'MATLAB:divideByZero'); szth = size(th); szth(1) = 1; if option.nobegin dht = [Inf(1,nc,np,nd0);dht]; % This infinite value at the beginning % prevents the selection of the first sample of data dhu = [Inf(1,nc,np,nd0);dhu]; th = [NaN(szth);th]; else dht = [-Inf(1,nc,np,nd0);dht]; % This infinite negative value at the beginning % ensures the selection of the first sample of data dhu = [-Inf(1,nc,np,nd0);dhu]; th = [NaN(szth);th]; end if option.noend dht = [dht;Inf(1,nc,np,nd0)]; % idem for the last sample of data dhu = [dhu;Inf(1,nc,np,nd0)]; th = [th;NaN(szth)]; else dht = [dht;-Inf(1,nc,np,nd0)]; dhu = [dhu;-Inf(1,nc,np,nd0)]; th = [th;NaN(szth)]; end nl0 = nl0+2; % Rearrange the 4th dimension (if used) into the 1st one. nl = nl0*nd0; dht4 = zeros(nl,nc,np); dhu4 = zeros(nl,nc,np); th2 = zeros(size(th)); for l = 1:nd0 dhu4((l-1)*nl0+(1:nl0)',:,:) = dhu(:,:,:,l); dht4((l-1)*nl0+(1:nl0)',:,:) = dht(:,:,:,l); th2((l-1)*nl0+(1:nl0)',:,:) = th(:,:,:); end dht = dht4; dhu = dhu4; th = th2; % The X-abscissa ddh = diff(dht); % Let's find the local maxima for l = 1:np dl = dht(2:end-1,:,l); for k = 1:nc dk = dl(:,k); mx{1,k,l} = find(and(and(dk >= option.cthr, ... dk >= option.thr),... ... dk <= option.lthr)), and(ddh(1:(end-1),k,l) > 0, ... ddh(2:end,k,l) <= 0)))+1; end end if option.cthr for l = 1:np for k = 1:nc finalmxk = []; mxk = mx{1,k,l}; if not(isempty(mxk)) wait = 0; if length(mxk)>5000 wait = waitbar(0,['Selecting peaks... (0 out of 0)']); end %if option.m < Inf % [unused,idx] = sort(dh(mxk,k,l),'descend'); % The peaks are sorted in decreasing order % mxk = mxk(sort(idx(1:option.m))); %end j = 1; % Scans the peaks from begin to end. mxkj = mxk(j); % The current peak jj = j+1; bufmin = Inf; bufmax = dht(mxkj,k,l); oldbufmin = min(dht(1:mxk(1)-1,k,l)); while jj <= length(mxk) if isa(wait,'matlab.ui.Figure') && not(mod(jj,5000)) waitbar(jj/length(mxk),wait,['Selecting peaks... (',num2str(length(finalmxk)),' out of ',num2str(jj),')']); end bufmin = min(bufmin, ... min(dht(mxk(jj-1)+1:mxk(jj)-1,k,l))); if bufmax - bufmin < option.cthr % There is no contrastive notch if dht(mxk(jj),k,l) > bufmax && ... (dht(mxk(jj),k,l) - bufmax > option.first ... || (bufmax - oldbufmin < option.cthr)) % If the new peak is significantly % higher than the previous one, % The peak is transfered to the new % position j = jj; mxkj = mxk(j); % The current peak bufmax = dht(mxkj,k,l); oldbufmin = min(oldbufmin,bufmin); bufmin = Inf; elseif dht(mxk(jj),k,l) - bufmax <= option.first bufmax = max(bufmax,dht(mxk(jj),k,l)); oldbufmin = min(oldbufmin,bufmin); end else % There is a contrastive notch if bufmax - oldbufmin < option.cthr % But the previous peak candidate % is too weak and therefore % discarded oldbufmin = min(oldbufmin,bufmin); else % The previous peak candidate is OK % and therefore stored finalmxk(end+1) = mxkj; oldbufmin = bufmin; end bufmax = dht(mxk(jj),k,l); j = jj; mxkj = mxk(j); % The current peak bufmin = Inf; end jj = jj+1; end if bufmax - oldbufmin >= option.cthr && ... bufmax - min(dht(mxk(j)+1:end,k,l)) >= option.cthr % The last peak candidate is OK and stored finalmxk(end+1) = mxk(j); end if isa(wait,'matlab.ui.Figure') waitbar(1,wait); close(wait); drawnow end end mx{1,k,l} = finalmxk; end end end if not(isempty(option.scan)) % 'ScanForward' option, used for 'Klapuri99' in mironsets for l = 1:np for k = 1:nc pscankl = pscan{i}{h}{1,k,l}; % scan seed positions mxkl = []; lp = length(pscankl); % number of peaks for jj = 1:lp % for each peak fmx = find(mx{1,k,l}>pscankl(jj),1); % position of the next max following the % current seed fmx = mx{1,k,l}(fmx); if jj<lp && (isempty(fmx) || fmx>=pscankl(jj+1)) [unused fmx] = max(dht(pscankl(jj):... pscankl(jj+1)-1,k,l)); fmx = fmx+pscankl(jj)-1; elseif jj==lp && isempty(fmx) [unused fmx] = max(dht(pscankl(jj):end,k,l)); fmx = fmx+pscankl(jj)-1; end mxkl = [mxkl fmx]; end mx{1,k,l} = mxkl; end end end if not(isequal(option.reso,0)) % Removing peaks too close to higher peaks if ischar(option.reso) && strcmpi(option.reso,'SemiTone') compar = @semitone_compar; elseif isnumeric(option.reso) compar = @dist_compar; end for l = 1:np for k = 1:nc [unused ind] = sort(dht(mx{1,k,l}),'descend'); mxlk = mx{1,k,l}(ind); del = []; j = 1; while j < length(mxlk) jj = j+1; while jj <= length(mxlk) if compar(th(mxlk(jj),k,l),th(mxlk(j),k,l),... option.reso) if option.resoloose mxlk(jj) = []; jj = jj-1; elseif option.resofirst && mxlk(j)>mxlk(jj) del = [del j]; else del = [del jj]; end end jj = jj+1; end j = j+1; end if ~option.resoloose mxlk(del) = []; end mx{1,k,l} = mxlk; end end end if not(isnan(option.near)) % Finding a peak nearest a given prefered location for l = 1:np for k = 1:nc mxlk = mx{1,k,l}; if strcmp(option.logsc,'Log') [M I] = min(abs(log(th(mxlk,k,l)/option.near))); else [M I] = min(abs(th(mxlk,k,l)-option.near)); end mx{1,k,l} = mxlk(I); end end end if option.harmo tp{i}{h} = cell(1,np); %if interpol tpp{i}{h} = cell(1,np); tpv{i}{h} = cell(1,np); %end for l = 1:np mxl = NaN(1,nc); txl = NaN(1,nc); myl = zeros(1,nc); segm = 0; for k = 1:nc mxk = mx{1,k,l}; txk = th(mxk,k); myk = dht(mxk,k); if isempty(mxk) continue end [maxk idx] = max(myk); if 0 %maxk < .7 continue end if idx > 1 if k > 1 && ~isempty(find(txl(:,k-1))) [unused r] = min(abs(txk(idx)-txl(:,k-1))); if r > 1 [unused ik] = min(abs(txk(idx)/r - th(:,k))); if dht(ik,k) / maxk > .8 mxl(1,k) = ik; txl(1,k) = th(ik,k); myl(1,k) = dht(ik,k); idx = 0; end end end if idx idxr = []; for n = 1:idx-1 if 0 %myk(n)/myk(idx) < .9 continue end harmo = mod(txk(idx)/txk(n),1); if round(txk(idx)/txk(n)) > 1 && ... (harmo <.25 || harmo > .75) idxr(end+1) = n; end end if ~isempty(idxr) [unused best] = max(myl(idxr)); idx = idxr(best); end end end %idx = find(myk>.7); %if isempty(idx) % continue %end %if k == 1 % idx = idx(1); %else % [unused c] = min(abs(txk(idx)-txl(1,k-1))); % idx = idx(c); %end if idx if ~segm segm = k; elseif 0 dist = abs(txk - txl(1,k-1)); [unused idx2] = min(dist); if idx2 ~= idx mat = max(txk(idx2),txl(1,k-1)); mit = min(txk(idx2),txl(1,k-1)); if mat/mit<1.025 idx = idx2; end end mat = max(txl(1,k-1),txk(idx)); mit = min(txl(1,k-1),txk(idx)); if mat/mit > 1.2 if k - segm < 2 mxl(:,segm:k-1) = NaN; txl(:,segm:k-1) = NaN; myl(:,segm:k-1) = 0; end segm = k; end end %ser = cell(1,length(mxk)); %for n1 = 1:length(mxk) % ser{n1} = 1; % for n2 = n1+1:length(mxk) % harmo = mod(txk(n2)/txk(n1),1); % rk = round(txk(n2)/txk(n1)); % if rk > 1 && ~ismember(rk,ser{n1}) && ... % harmo <.2 || harmo > .8 % ser{n1}(end+1) = rk; % end % end %end %ser; mxl(1,k) = mxk(idx)-1; txl(1,k) = txk(idx); myl(1,k) = myk(idx); end for n = 1:length(mxk) if mxk(n) <= mxl(1,k) continue end harmo = mod(txk(n)/txl(1,k),1); rk = round(txk(n)/txl(1,k)); if ((size(mxl,1) < rk || myk(n) > myl(rk,k)) && ... harmo <.25 || harmo > .75) && ... rk <= option.harmo if rk > size(mxl,1) mxl(size(mxl)+1:rk,:) = NaN; txl(size(mxl)+1:rk,:) = NaN; myl(size(mxl)+1:rk,:) = 0; end mxl(rk,k) = mxk(n); txl(rk,k) = txk(n); myl(rk,k) = myk(n); end end if size(myl,1) > 2 && myl(2,k) == NaN mxl(:,k) = NaN; txl(:,k) = NaN; myl(:,k) = NaN; end end tp{i}{h}{l} = mxl; tpp{i}{h}{l} = txl; tv{i}{h}{l} = myl; tpv{i}{h}{l} = myl; end elseif option.delta % Peak tracking tp{i}{h} = cell(1,np); if interpol tpp{i}{h} = cell(1,np); tpv{i}{h} = cell(1,np); end for l = 1:np % mxl will be the resulting track position matrix % and myl the related track amplitude % In the first frame, tracks can be identified to peaks. mxl = mx{1,1,l}(:)-1; myl = dht(mx{1,1,l}(:),k,l); % To each peak is associated the related track ID tr2 = 1:length(mx{1,1,l}); grvy = []; % The graveyard. wait = 0; if nc-1>500 wait = waitbar(0,['Tracking peaks...']); end for k = 1:nc-1 % For each successive frame... if not(isempty(grvy)) old = find(grvy(:,2) == k-option.mem-1); grvy(old,:) = []; end if wait && not(mod(k,100)) waitbar(k/(nc-1),wait); end mxk1 = mx{1,k,l}; % w^k mxk2 = mx{1,k+1,l}; % w^{k+1} thk1 = th(mxk1,k,l); thk2 = th(mxk2,k,l); matched = zeros(size(thk2)); myk2 = dht(mx{1,k+1,l},k,l); % amplitude tr1 = tr2; tr2 = NaN(1,length(mxk2)); mxl(:,k+1) = mxl(:,k); if isempty(thk1) || isempty(thk2) %% IS THIS TEST NECESSARY?? myl(:,k+1) = 0; else for n = 1:length(mxk1) % Let's check each track. tr = tr1(n); % Current track. if not(isnan(tr)) % track currently active % Step 1 in Mc Aulay & Quatieri [int m] = min(abs(thk2-thk1(n))); % Finding w^{k+1} closest to current w^k if isinf(int) || int > option.delta % all w^{k+1} outside matching interval: % partial becomes inactive mxl(tr,k+1) = mxl(tr,k); myl(tr,k+1) = 0; grvy = [grvy; tr k]; % added to the graveyard else [best mm] = min(abs(thk2(m)-th(mxk1,k,l))); % the mmth peak in frame k is the closest to w^{k+1} % Let's first test whether candidate % match w^{k+1} is particularly closed to an inactive track. (Lartillot) if isempty(grvy) testprev = 0; else [best2 mm2] = min(abs(thk2(m)-th(mxl(grvy(:,1),k),k,l))); if best2 < best oldk = grvy(mm2,2); if mxl(tr,oldk) oldt1 = th(mxl(grvy(mm2,1),oldk),oldk,l); oldt2 = th(mxl(tr,oldk),oldk,l); dif1 = abs(oldt1-thk2(m)); dif2 = abs(oldt2-thk2(m)); if dif1 < dif2 testprev = 1; end else testprev = 1; end else testprev = 0; end end if testprev % Yes, candidate match w^{k+1} is particularly closed to an inactive track. (Lartillot) otr = grvy(mm2,1); mxl(otr,k+1) = mxk2(m)-1; myl(otr,k+1) = myk2(m); tr2(m) = otr; thk2(m) = Inf; % selected w^{k+1} is eliminated from further consideration matched(m) = 1; grvy(mm2,:) = []; else % Step 2 in Mc Aulay & Quatieri if option.fuse || mm == n % candidate match w^{k+1} is not closer to any remaining w^k: % definite match mxl(tr,k+1) = mxk2(m)-1; myl(tr,k+1) = myk2(m); tr2(m) = tr; matched(m) = 1; if ~option.fuse thk1(n) = -Inf; % selected w^k is eliminated from further consideration thk2(m) = Inf; % selected w^{k+1} is eliminated as well end if not(isempty(grvy)) zz = find ((mxl(grvy(:,1),k) >= mxl(tr,k) & ... mxl(grvy(:,1),k) <= mxl(tr,k+1)) | ... (mxl(grvy(:,1),k) <= mxl(tr,k) & ... mxl(grvy(:,1),k) >= mxl(tr,k+1))); grvy(zz,:) = []; end end if ~option.fuse && mm ~= n % candidate match w^{k+1} is closer to another w^k % let's look at adjacent lower w^{k+1}... [int mmm] = min(abs(thk2(1:m)-thk1(n))); if int > best || ... % New condition added (Lartillot 16.4.2010) isinf(int) || ... % Conditions proposed in Mc Aulay & Quatieri (all w^{k+1} below matching interval) int > option.delta % no other suitable candidate match w^{k+1} found % partial becomes inactive mxl(tr,k+1) = mxl(tr,k); myl(tr,k+1) = 0; grvy = [grvy; tr k]; % added to the graveyard else % definite match mxl(tr,k+1) = mxk2(mmm)-1; myl(tr,k+1) = myk2(mmm); tr2(mmm) = tr; thk1(n) = -Inf; % selected w^k is eliminated from further consideration thk2(mmm) = Inf; % selected w^{k+1} is eliminated as well matched(mmm) = 1; if not(isempty(grvy)) zz = find ((mxl(grvy(:,1),k) >= mxl(tr,k) & ... mxl(grvy(:,1),k) <= mxl(tr,k+1)) | ... (mxl(grvy(:,1),k) <= mxl(tr,k) & ... mxl(grvy(:,1),k) >= mxl(tr,k+1))); grvy(zz,:) = []; end end end end end end end end % Step 3 in Mc Aulay & Quatieri for m = 1:length(mxk2) if ~matched(m) % unmatched w^{k+1} if isempty(grvy) int = []; else % Let's try to reuse an inactive track from the % graveyard (Lartillot). [int z] = min(abs(th(mxl(grvy(:,1),k+1)+1,k,l)-thk2(m))); end if isempty(int) || int > option.delta ... || int > min(abs(th(mxl(:,k+1)+1,k,l)-thk2(m))) % No suitable inactive track. % birth of a new partial (Mc Aulay & % Quatieri) mxl = [mxl;zeros(1,k+1)]; tr = size(mxl,1); mxl(tr,k) = mxk2(m)-1; else % Suitable inactive track found, turned active. (Lartillot) tr = grvy(z,1); grvy(z,:) = []; end mxl(tr,k+1) = mxk2(m)-1; myl(tr,k+1) = myk2(m); tr2(m) = tr; end end end if wait waitbar(1,wait); close(wait); drawnow end if size(mxl,1) > option.m tot = sum(myl,2); [tot ix] = sort(tot,'descend'); mxl(ix(option.m+1:end),:) = []; myl(ix(option.m+1:end),:) = []; end mxl(:,not(max(myl))) = 0; if option.shorttrackthresh [myl bestrack] = max(myl,[],1); mxl = mxl(bestrack + (0:size(mxl,2)-1)*size(mxl,1)); changes = find(not(bestrack(1:end-1) == bestrack(2:end)))+1; if not(isempty(changes)) lengths = diff([1 changes nc+1]); shorts = find(lengths < option.shorttrackthresh); for k = 1:length(shorts) if shorts(k) == 1 k1 = 1; else k1 = changes(shorts(k)-1); end k2 = k1 + lengths(shorts(k)) -1; myl(1,k1:k2) = 0; mxl(1,k1:k2) = 0; end end end tp{i}{h}{l} = mxl; tv{i}{h}{l} = myl; if interpol tpv{i}{h}{l} = zeros(size(mxl)); tpp{i}{h}{l} = zeros(size(mxl)); for k = 1:size(mxl,2) for j = 1:size(mxl,1) if myl(j,k) mj = mxl(j,k); if mj>2 && mj<size(dhu,1)-1 % More precise peak position y0 = dhu(mj,k,l); ym = dhu(mj-1,k,l); yp = dhu(mj+1,k,l); p = (yp-ym)/(2*(2*y0-yp-ym)); tpv{i}{h}{l}(j,k) = y0 - 0.25*(ym-yp)*p; if p >= 0 tpp{i}{h}{l}(j,k) = (1-p)*th(mj,k,l)+p*th(mj+1,k,l); elseif p < 0 tpp{i}{h}{l}(j,k) = (1+p)*th(mj,k,l)-p*th(mj-1,k,l); end elseif mj tpv{i}{h}{l}(j,k) = dhu(mj,k,l); tpp{i}{h}{l}(j,k) = th(mj,k,l); end else tpv{i}{h}{l}(j,k) = 0; tpp{i}{h}{l}(j,k) = NaN; end end end end end end if isa(x,'mirsimatrix') && option.graph % Finding the best branch inside a graph constructed out of a % similarity matrix g{i}{h} = cell(1,nc,np); % Branch info related to each peak br{i}{h} = {}; % Info related to each branch scog{i}{h} = cell(1,nc,np); % Score related to each peak scob{i}{h} = []; % Score related to each branch for l = 1:np wait = waitbar(0,['Creating peaks graph...']); for k = 1:nc g{i}{h}{1,k,l} = cell(size(mx{1,k,l})); scog{i}{h}{1,k,l} = zeros(size(mx{1,k,l})); if wait && not(mod(k,50)) waitbar(k/(nc-1),wait); end mxk = mx{1,k,l}; % Peaks in current frame for j = k-1:-1:max(1,k-10) % Recent frames mxj = mx{1,j,l}; % Peaks in one recent frame for kk = 1:length(mxk) mxkk = mxk(kk); % For each of current peaks if mxkk < 10 continue end for jj = 1:length(mxj) mxjj = mxj(jj); % For each of recent peaks sco = k-j - abs(mxkk-mxjj); % Crossprogression from recent to % current peak if sco >= 0 % Negative crossprogression excluded dist = 0; % The distance between recent and % current peak is the sum of all the % simatrix values when joining the two % peaks with a straight line. for m = j:k % Each point in that straight line. mxm = mxjj + (mxkk-mxjj)*(m-j)/(k-j); if mxm == floor(mxm) dist = dist + 1-dht(mxm,m,l); else dhm0 = dht(floor(mxm),m,l); dhm1 = dht(ceil(mxm),m,l); dist = dist + 1-... (dhm0 + ... (dhm1-dhm0)*(mxm-floor(mxm))); end if dist > option.graph break end end if dist < option.graph % If the distance between recent % and current peak is not too high, % a new edge is formed between the % peaks, and added to the graph. gj = g{i}{h}{1,j,l}{jj}; % Branch information associated % with recent peak gk = g{i}{h}{1,k,l}{kk}; % Branch information associated % with current peak if isempty(gk) || ... sco > scog{i}{h}{1,k,l}(kk) % Current peak branch to be updated if isempty(gj) % New branch starting % from scratch newsco = sco; scob{i}{h}(end+1) = newsco; bid = length(scob{i}{h}); g{i}{h}{1,j,l}{jj} = ... [k kk bid newsco]; br{i}{h}{bid} = [j jj;k kk]; else newsco = scog{i}{h}{1,j,l}(jj)+sco; if length(gj) == 1 % Recent peak not % associated with other % branch % -> Branch extension bid = gj; g{i}{h}{1,j,l}{jj} = ... [k kk bid newsco]; br{i}{h}{bid}(end+1,:) = [k kk]; else % Recent peak already % associated with other % branch % -> Branch fusion bid = length(scob{i}{h})+1; g{i}{h}{1,j,l}{jj} = ... [k kk bid newsco; gj]; other = br{i}{h}{gj(1,3)}; % Other branch % info % Let's copy its % prefix to the new % branch: other(other(:,1)>j,:) = []; br{i}{h}{bid} = [other;k kk]; end scob{i}{h}(bid) = newsco; end g{i}{h}{1,k,l}{kk} = bid; % New peak associated with % branch scog{i}{h}{1,k,l}(kk) = newsco; end end end end end end end [scob{i}{h} IX] = sort(scob{i}{h},'descend'); if length(IX) > option.m scob{i}{h} = scob{i}{h}(1:option.m); IX = IX(1:option.m); end % Branch are ordered from best score to lowest br{i}{h} = br{i}{h}(IX); if wait waitbar(1,wait); close(wait); drawnow end end end if ~option.graph for l = 1:np % Orders the peaks and select the best ones for k = 1:nc mxk = mx{1,k,l}; if length(mxk) > option.m [unused,idx] = sort(dht(mxk,k,l),'descend'); idx = idx(1:option.m); elseif strcmpi(option.order,'Amplitude') [unused,idx] = sort(dht(mxk,k,l),'descend'); else idx = 1:length(dht(mxk,k,l)); end if strcmpi(option.order,'Abscissa') mx{1,k,l} = sort(mxk(idx)); elseif strcmpi(option.order,'Amplitude') mx{1,k,l} = mxk(idx); end end end end if option.extract % Extracting the positive part of the curve containing the peaks if isa(x,'mirtemporal') filn = floor(sr{i}/25); else filn = 10; end if filn>1 && size(dhu,1)>5 filn = min(filn,floor(size(dhu,1)/3)); fild = filtfilt(ones(1,filn)/2,1,dhu(2:end-1,:,:))/filn/2; else fild = dhu(2:end-1,:,:); end fild = [zeros(1,size(fild,2),size(fild,3));diff(fild)]; for l = 1:np for k = 1:nc idx = 1:size(dht,1); mxlk = sort(mx{1,k,l}-1); for j = 1:length(mxlk) if fild(mxlk(j),k,l) < 0 bef0 = find(fild(1:mxlk(j)-1,k,l)>=0); if isempty(bef0) bef0 = []; end else bef0 = mxlk(j)-1; end if isempty(bef0) bef = 0; else bef = find(fild(1:bef0(end),k,l)<=0); if isempty(bef) bef = 0; end end if j>1 && bef(end)<aft(1)+2 idx(mxlk(j-1):mxlk(j)) = 0; [unused btw] = min(dhu(mxlk(j-1)+1:mxlk(j)+1,k,l)); btw = btw+mxlk(j-1); idx(btw-2:btw+2) = btw-2:btw+2; bef = btw+2; end if fild(mxlk(j),k,l) > 0 aft0 = find(fild(mxlk(j)+1:end,k,l)<=0)+mxlk(j); if isempty(aft0) aft0 = []; end else aft0 = mxlk(j)+1; end if isempty(aft0) aft = size(d{i}{h},1)+1; else aft = find(fild(aft0(1):end,k,l)>=0)+mxlk(j); if isempty(aft) aft = size(d{i}{h},1)+1; end end idx(bef(end)+3:aft(1)-3) = 0; end idx = idx(find(idx)); dhu(idx,k,l) = NaN; end end end if option.vall dhu = -dhu; end mmx = cell(1,nc,np); mmy = cell(1,nc,np); mmv = cell(1,nc,np); for l = 1:np for k = 1:nc mmx{1,k,l} = mod(mx{1,k,l}(:,:,1),nl0)-1; mmy{1,k,l} = ceil(mx{1,k,l}/nl0); mmv{1,k,l} = dhu(mx{1,k,l}(:,:,1),k,l); end end pp{i}{h} = mmx; pm{i}{h} = mmy; pv{i}{h} = mmv; if not(interpol) ppp{i}{h} = {}; ppv{i}{h} = {}; else % Interpolate to find the more exact peak positions pih = cell(1,nc,np); vih = cell(1,nc,np); for l = 1:np for k = 1:nc mxlk = mx{1,k,l}; vih{1,k,l} = zeros(length(mxlk),1); pih{1,k,l} = zeros(length(mxlk),1); for j = 1:length(mxlk) mj = mxlk(j); % Current values if strcmpi(option.interpol,'quadratic') if mj>2 && mj<size(dhu,1)-1 % More precise peak position y0 = dhu(mj,k,l); ym = dhu(mj-1,k,l); yp = dhu(mj+1,k,l); p = (yp-ym)/(2*(2*y0-yp-ym)); vih(1,k,l).(num2str(j)) = y0 - 0.25*(ym-yp)*p; if p >= 0 pih(1,k,l).(num2str(j)) = (1-p)*th(mj,k,l)+p*th(mj+1,k,l); elseif p < 0 pih(1,k,l).(num2str(j)) = (1+p)*th(mj,k,l)-p*th(mj-1,k,l); end else vih(1,k,l).(num2str(j)) = dhu(mj,k,l); pih(1,k,l).(num2str(j)) = th(mj,k,l); end end end end end ppp{i}{h} = pih; ppv{i}{h} = vih; end if not(iscell(d{i})) % for chromagram d{i} = dhu(2:end-1,:,:,:); else if cha == 1 d{i}{h} = zeros(1,size(dhu,2),size(dhu,1)-2); for k = 1:size(dhu,2) d{i}{h}(1,k,:) = dhu(2:end-1,k); end else d{i}{h} = dhu(2:end-1,:,:,:); end end if option.only dih = zeros(size(d{i}{h})); for l = 1:np for k = 1:nc dih(pp{i}{h}{1,k,l},k,l) = ... d{i}{h}(pp{i}{h}{1,k,l},k,l); end end d{i}{h} = dih; end end end p = set(x,'PeakPos',pp,'PeakVal',pv,'PeakMode',pm); if interpol p = set(p,'PeakPrecisePos',ppp,'PeakPreciseVal',ppv); end if option.extract p = set(p,'Data',d); end empty = cell(1,length(d)); if option.only p = set(p,'Data',d,'PeakPos',empty,'PeakVal',empty,'PeakMode',empty); end if option.harmo || option.delta p = set(p,'TrackPos',tp,'TrackVal',tv); if interpol p = set(p,'TrackPrecisePos',tpp,'TrackPreciseVal',tpv); end end if isa(x,'mirsimatrix') && option.graph p = set(p,'Graph',g,'Branch',br); end function y = semitone_compar(p1,p2,thres) y = max(p1,p2)/min(p1,p2) < 2^(1/12); function y = dist_compar(p1,p2,thres) y = abs(p1-p2) < thres;
github
martinarielhartmann/mirtooloct-master
mirroughness.m
.m
mirtooloct-master/MIRToolbox/mirroughness.m
4,303
utf_8
16c3687ea66082d446f11b615c72a443
function varargout = mirroughness(x,varargin) % r = mirroughness(x) calculates the roughness, or sensory dissonance, % due to beating phenomenon between close frequency peaks. % The frequency components are supposed to remain sufficiently % constant throughout each frame of each audio file. % r = mirroughness(...,'Contrast',c) specifies the contrast parameter % used for peak picking (cf. mirpeaks). % Default value: c = .01 % [r,s] = mirroughness(x) also displays the spectrum and its peaks, used % for the computation of roughness. % Optional arguments: % Method used: % mirroughness(...,'Sethares') (default): based on the summation % of roughness between all pairs of sines (obtained through % spectral peak-picking). % mirroughness(...,'Min'): Variant of the Sethares model % where the summation is weighted by the minimum % amplitude of each pair of sines, instead of the product % of their amplitudes. % mirroughness(...,'Vassilakis'): variant of 'Sethares' model % with a more complex weighting (Vassilakis, 2001, Eq. 6.23). meth.type = 'String'; meth.choice = {'Sethares','Vassilakis'}; meth.default = 'Sethares'; option.meth = meth; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = .01; option.cthr = cthr; omin.key = 'Min'; omin.type = 'Boolean'; omin.default = 0; option.min = omin; normal.key = 'Normal'; normal.type = 'Boolean'; normal.default = 0; option.normal = normal; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [.05 .5]; option.frame = frame; specif.option = option; specif.defaultframelength = .05; specif.defaultframehop = .5; varargout = mirfunction(@mirroughness,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if isamir(x,'miraudio') && not(isframed(x)) x = mirframenow(x,option); end x = mirspectrum(x); if not(haspeaks(x)) x = mirpeaks(x,'Contrast',option.cthr); end type = {'mirscalar','mirspectrum'}; function r = main(p,option,postoption) if iscell(p) p = p{1}; end if strcmpi(option.meth,'Sethares') || strcmpi(option.meth,'Vassilakis') pf = get(p,'PeakPosUnit'); pv = get(p,'PeakVal'); if option.normal d = get(p,'Data'); end rg = cell(1,length(pf)); for h = 1:length(pf) rg{h} = cell(1,length(pf{h})); for i = 1:length(pf{h}) pfi = pf{h}{i}; pvi = pv{h}{i}; rg{h}{i} = zeros(1,length(pfi)); for k = 1:size(pfi,3) for j = 1:size(pfi,2) pfj = pfi{1,j,k}'; pvj = pvi{1,j,k}; f1 = repmat(pfj,[1 length(pfj)]); f2 = repmat(pfj',[length(pfj) 1]); v1 = repmat(pvj,[1 length(pvj)]); v2 = repmat(pvj',[length(pvj) 1]); rj = plomp(f1,f2); if option.min v12 = min(v1,v2); else v12 = v1.*v2; end if strcmpi(option.meth,'Sethares') rj = v12.*rj; elseif strcmpi(option.meth,'Vassilakis') rj = (v1.*v2).^.1.*.5.*(2*v2./(v1+v2)).^3.11.*rj; end rg{h}{i}(1,j,k) = sum(sum(rj)); if option.normal rg{h}{i}(1,j,k) = rg{h}{i}(1,j,k) ... / sum(d{h}{i}(:,j,k).^2); .../ sum(sum(triu(v1.*v2,1))); end end end end end else end r = mirscalar(p,'Data',rg,'Title','Roughness'); r = {r,p}; function pd = plomp(f1, f2) % returns the dissonance of two pure tones at frequencies f1 & f2 Hz % according to the Plomp-Levelt curve (see Sethares) b1 = 3.51; b2 = 5.75; xstar = .24; s1 = .0207; s2 = 18.96; s = tril(xstar ./ (s1 * min(f1,f2) + s2 )); pd = exp(-b1*s.*abs(f2-f1)) - exp(-b2*s.*abs(f2-f1));
github
martinarielhartmann/mirtooloct-master
mirfluctuation.m
.m
mirtooloct-master/MIRToolbox/mirfluctuation.m
4,524
utf_8
bceb1ff305659e1156a294910325c9ab
function varargout = mirfluctuation(orig,varargin) % f = mirfluctuation(x) calculates the fluctuation strength, indicating % the rhythmic periodicities along the different channels. % Optional arguments: % mirfluctuation(...,'MinRes',mr) specifies the minimal frequency % resolution of the resulting spectral decomposition, in Hz. % Default: mr = .01 Hz % mirfluctuation(...,'Summary') returns the summary of the % fluctuation, i.e., the summation along the critical bands. % mirfluctuation(..., 'InnerFrame', l, r) specifies the spectrogram % frame length l (in second), and, optionally, the frame rate r % (in Hertz), with by default a frame length of 23 ms and a frame % rate of 80 Hz. % mirfluctuation(..., 'Frame', l, r) computes fluctuation using a % window moving along the spectrogram, whose length l (in second) % and frame rate r (in Hertz) can be specified as well, with by % default a frame length of 1 s and a frame rate of 10 Hz. % % E. Pampalk, A. Rauber, D. Merkl, "Content-based Organization and % Visualization of Music Archives", sum.key = 'Summary'; sum.type = 'Boolean'; sum.default = 0; option.sum = sum; mr.key = 'MinRes'; mr.type = 'Integer'; mr.default = .01; option.mr = mr; max.key = 'Max'; max.type = 'Integer'; max.default = 10; option.max = max; band.type = 'String'; band.choice = {'Mel','Bark'}; band.default = 'Bark'; option.band = band; inframe.key = 'InnerFrame'; inframe.type = 'Integer'; inframe.number = 2; inframe.default = [.023 80]; option.inframe = inframe; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [1 10]; option.frame = frame; specif.option = option; specif.nochunk = 1; varargout = mirfunction(@mirfluctuation,orig,varargin,nargout,specif,@init,@main); function [s type] = init(x,option) if iscell(x) x = x{1}; end if option.inframe(2) < option.max * 2 option.inframe(2) = option.max * 2; end if isamir(x,'miraudio') && not(isframed(x)) x = mirframe(x,option.inframe(1),'s',option.inframe(2),'Hz'); end s = mirspectrum(x,'Power','Terhardt',option.band,'dB','Mask'); type = 'mirspectrum'; function f = main(x,option,postoption) d = get(x,'Data'); fp = get(x,'FramePos'); fl = option.frame.length.val; fh = option.frame.hop.val; if ~fl f = mirspectrum(x,'AlongBands','Max',option.max,... 'Window',0,'NormalLength',... 'Resonance','Fluctuation','MinRes',option.mr); else vb = mirverbose; mirverbose(0); df = cell(1,length(d)); fp2 = cell(1,length(d)); p2 = cell(1,length(d)); for i = 1:length(d) df{i} = cell(1,length(d{i})); fp2{i} = cell(1,length(d{i})); for j = 1:length(d{i}) dur = fp{i}{j}(1,end) - fp{i}{j}(1,1); srj = size(d{i}{j},2) / dur; % Inner frame rate flj = round(fl * srj); % Outer frame length in number of inner frames fhj = srj / fh; % Outer hop factor in number of inner frames n = floor((dur - fl) * fh ) + 1; % Number of outer frames fp2{i}{j} = zeros(2,n); for k = 1:n % For each outer frame, ... st = round( (k-1) * fhj) + 1; stend = st + flj - 1; dk = d{i}{j}(:,st:stend,:); fpk = fp{i}{j}(:,st:stend); x2 = set(x,'Data',{{dk}},'FramePos',{{fpk}}); fk = mirspectrum(x2,'AlongBands','Max',10,'Window',0,... 'NormalLength',... 'Resonance','Fluctuation',... 'MinRes',option.mr); dfk = mirgetdata(fk); if k == 1 df{i}{j} = zeros(size(dfk,1),n,size(dfk,3)); end df{i}{j}(:,k,:) = dfk; fp2{i}{j}(:,k) = [fpk(1);fpk(end)]; end p = get(fk,'Pos'); p2{i}{j} = repmat(p{1}{1},[1 n 1]); end end f = set(fk,'Data',df,'FramePos',fp2,'Pos',p2); mirverbose(vb); end if option.sum f = mirsummary(f); end f = set(f,'Title','Fluctuation');
github
martinarielhartmann/mirtooloct-master
mirstd.m
.m
mirtooloct-master/MIRToolbox/mirstd.m
2,348
utf_8
bd448049bf264e4092658cccfabdf692
function varargout = mirstd(f,varargin) % m = mirstd(f) returns the standard deviation along frames of the feature f % % f can be a structure array composed of features. In this case, % m will be structured the same way. if isa(f,'mirstruct') data = get(f,'Data'); for fi = 1:length(data) data{fi} = mirstd(data{fi}); end varargout = {set(f,'Data',data)}; elseif isstruct(f) fields = fieldnames(f); for i = 1:length(fields) field = fields{i}; stat.(field) = mirstd(f.(field)); end varargout = {stat}; else normdiff.key = 'NormDiff'; normdiff.type = 'Boolean'; normdiff.default = 0; specif.option.normdiff = normdiff; specif.nochunk = 1; varargout = mirfunction(@mirstd,f,varargin,nargout,specif,@init,@main); end function [x type] = init(x,option) type = ''; function m = main(f,option,postoption) if iscell(f) f = f{1}; end if isa(f,'mirhisto') warning('WARNING IN MIRSTD: histograms are not taken into consideration yet.') m = struct; return end fp = get(f,'FramePos'); ti = get(f,'Title'); d = get(f,'Data'); l = length(d); for i = 1:l if iscell(d{i}) if length(d{i}) > 1 error('ERROR IN MIRSTD: segmented data not accepted yet.'); else dd = d{i}{1}; end else dd = d{i}; end if iscell(dd) m{i} = {zeros(1,length(dd))}; for j = 1:length(dd) m{i}{1}(j) = std(dd{j}); end elseif size(dd,2) < 2 nonan = find(not(isnan(dd))); dn = dd(nonan); if option.normdiff m{i}{1} = norm(diff(dn,2)); else m{i}{1} = std(dn,0,2); end else dd = mean(dd,4); m{i} = {NaN(size(dd,1),1,size(dd,3))}; for k = 1:size(dd,1) for l = 1:size(dd,3) dk = dd(k,:,l); nonan = find(not(isnan(dk))); if not(isempty(nonan)) dn = dk(nonan); if option.normdiff m{i}{1}(k,1,l) = norm(diff(dn,2)); else m{i}{1}(k,1,l) = std(dn,0,2); end end end end end end m = mirscalar(f,'Data',m,'Title',['Standard deviation of ',ti]);
github
martinarielhartmann/mirtooloct-master
mirfeatures.m
.m
mirtooloct-master/MIRToolbox/mirfeatures.m
4,420
utf_8
66e50462e85b091a22d7aafb3a72c400
function r = mirfeatures(x,varargin) % f = mirfeatures(x) computes a large set of features from one or several % audio files. x can be either the name of an audio file, or the % 'Folder' keyword. % mirfeatures(...,'Stat') returns the statistics of the features instead % of the complete features themselves. % mirfeatures(...,'Segment',t) segments the audio sequence at the % temporal positions indicated in the array t (in s.), and analyzes % each segment separately. %(not available yet) % mirfeatures(...,'Filterbank',nc) computes the analysis on each channel % of a filterbank decomposition. % Default value: nc = 5 % mirfeatures(...,'Frame',...) % mirfeatures(...,'Normal') % mirfeatures(...,'Sampling',s) % miraudio options (Extract, ...) [stat,nchan,segm,feat] = scanargin(varargin); if isa(x,'miraudio') || isa(x,'mirdesign') a = miraudio(x,'Normal'); % normalize with respect to RMS energy % in order to consider timbre independently of % energy else a = miraudio('Design','Normal'); end if not(isempty(segm)) a = mirsegment(a,segm); end % DYNAMICS % -------- r.dynamics.rms = mirrms(a,'Frame'); % Perceived dynamics: spectral slope? % RHYTHM % ------ r.fluctuation = mirstruct; r.fluctuation.tmp.f = mirfluctuation(a,'Summary'); r.fluctuation.peak = mirpeaks(r.fluctuation.tmp.f,'Total',1);%only one? r.fluctuation.centroid = mircentroid(r.fluctuation.tmp.f); r.rhythm = mirstruct; r.rhythm.tmp.onsets = mironsets(a); %r.rhythm.eventdensity = ... r.rhythm.tempo = mirtempo(r.rhythm.tmp.onsets,'Frame'); %r.rhythm.pulseclarity = mirpulseclarity(r.tmp.onsets,'Frame'); % Should use the second output of mirtempo. attacks = mironsets(r.rhythm.tmp.onsets,'Attacks'); r.rhythm.attack.time = mirattacktime(attacks); r.rhythm.attack.slope = mirattackslope(attacks); % TIMBRE % ------ f = mirframe(a,.05,.5); r.spectral = mirstruct; r.spectral.tmp.s = mirspectrum(f); %pitch = mirpitch(a,'Frame',.05,.5); r.spectral.centroid = mircentroid(r.spectral.tmp.s); r.spectral.brightness = mirbrightness(r.spectral.tmp.s); r.spectral.spread = mirspread(r.spectral.tmp.s); r.spectral.skewness = mirskewness(r.spectral.tmp.s); r.spectral.kurtosis = mirkurtosis(r.spectral.tmp.s); r.spectral.rolloff95 = mirrolloff(r.spectral.tmp.s,'Threshold',95); r.spectral.rolloff85 = mirrolloff(r.spectral.tmp.s,'Threshold',85); r.spectral.spectentropy = mirentropy(r.spectral.tmp.s); r.spectral.flatness = mirflatness(r.spectral.tmp.s); r.spectral.roughness = mirroughness(r.spectral.tmp.s); r.spectral.irregularity = mirregularity(r.spectral.tmp.s); %r.spectral.inharmonicity = mirinharmonicity(r.spectral.tmp.s,'f0',pitch); r.spectral.mfcc = mirmfcc(r.spectral.tmp.s); r.spectral.dmfcc = mirmfcc(r.spectral.mfcc,'Delta'); r.spectral.ddmfcc = mirmfcc(r.spectral.dmfcc,'Delta'); r.timbre.zerocross = mirzerocross(f); r.timbre.lowenergy = mirlowenergy(f); r.timbre.spectralflux = mirflux(f); % PITCH % ----- r.tonal = mirstruct; r.tonal.tmp.chromagram = mirchromagram(a,'Frame','Wrap',0,'Pitch',0); r.tonal.chromagram.peak = mirpeaks(r.tonal.tmp.chromagram,'Total',1); r.tonal.chromagram.centroid = mircentroid(r.tonal.tmp.chromagram); % TONALITY/HARMONY % ---------------- keystrengths = mirkeystrength(r.tonal.tmp.chromagram); [k r.tonal.keyclarity] = mirkey(keystrengths,'Total',1); %r.tonal.keyclarity = k{2}; r.tonal.mode = mirmode(keystrengths); r.tonal.hcdf = mirhcdf(r.tonal.tmp.chromagram); if stat r = mirstat(r); % SHOULD COMPUTE STAT OF CURVES FROM FRAMED_DECOMPOSED HIGH FEATURES end if not(isa(x,'miraudio')) && not(isa(x,'mirdesign')) r = mireval(r,x); end function [stat,nchan,segm,feat] = scanargin(v) stat = 0; nchan = 1; segm = []; feat = {}; i = 1; while i <= length(v) arg = v{i}; if ischar(arg) && strcmpi(arg,'Filterbank') i = i+1; if i <= length(v) nchan = v{i}; else nchan = 10; end elseif ischar(arg) && strcmpi(arg,'Stat') i = i+1; if i <= length(v) stat = v{i}; else stat = 1; end elseif ischar(arg) && strcmpi(arg,'Segment') i = i+1; if i <= length(v) segm = v{i}; else segm = 1; end else feat{end+1} = arg; end i = i+1; end
github
martinarielhartmann/mirtooloct-master
mirfunction.m
.m
mirtooloct-master/MIRToolbox/mirfunction.m
7,438
utf_8
022bac1efaf28f4badabfaa0eb4ba0a8
function o = mirfunction(method,x,varg,nout,specif,init,main) % Meta function called by all MIRtoolbox functions. % Integrates the function into the general flowchart % and eventually launches the "mireval" evaluation process. % Here are the successive steps in the following code: % - If the input is an audio filename, instantiates a new design flowchart. % - Reads all the options specified by the user. % - Performs the 'init' part of the MIRtoolbox function: % - If the input is a design flowchart, % add the 'init' part in the flowchart. % - If the input is some MIRtoolbox data, % execute the 'init' part on that data. % - Performs the 'main' part of the MIRtoolbox function. if isempty(x) o = {{},{},{}}; return end if ischar(x) || ... (iscell(x) && ischar(x{1})) % The input is a file name. % Starting point of the design process design_init = 1; filename = x; if strcmpi(func2str(method),'miraudio') postoption = {}; else postoption.mono = 1; end orig = mirdesign(@miraudio,'Design',{varg},postoption,struct,'miraudio'); % Implicitly, the audio file needs to be loaded first. elseif isnumeric(x) && ~isequal(method,@mirsimatrix) mirerror(func2str(method),'The input should be a file name or a MIRtoolbox object.'); else design_init = 0; orig = x; end % Reads all the options specified by the user. [orig during after] = miroptions(method,orig,specif,varg); % Performs the 'init' part of the MIRtoolbox function. if isa(orig,'mirdesign') if not(get(orig,'Eval')) % Top-down construction of the general design flowchart if isstruct(during) && isfield(during,'frame') && ... isstruct(during.frame) && during.frame.auto % 'Frame' option: % Automatic insertion of the mirframe step in the design orig = mirframe(orig,during.frame.length.val,... during.frame.length.unit,... during.frame.hop.val,... during.frame.hop.unit,... during.frame.phase.val,... during.frame.phase.unit,... during.frame.phase.atend); end % The 'init' part of the function can be integrated into the design % flowchart. This leads to a top-down construction of the % flowchart. % Automatic development of the implicit prerequisites, % with management of the data types throughout the design process. [orig type] = init(orig,during); o = mirdesign(method,orig,during,after,specif,type); if design_init && ... not(ischar(filename) && strcmpi(filename,'Design')) % Now the design flowchart has been completed created. % If the 'Design' keyword not used, % the function is immediately evaluated o = mireval(o,filename,nout); else o = returndesign(o,nout); end if not(iscell(o)) o = {o}; end return else % During the top-down traversal of the flowchart (evaleach), at the % beginning of the evaluation process. if not(isempty(get(orig,'TmpFile'))) && get(orig,'ChunkDecomposed') orig = evaleach(orig); if iscell(orig) orig = orig{1}; end x = orig; else [orig x] = evaleach(orig); end if not(isequal(method,@nthoutput)) if iscell(orig) orig = orig{1}; end if isempty(get(orig,'InterChunk')) orig = set(orig,'InterChunk',get(x,'InterChunk')); end end end else design = 0; if iscell(orig) i = 0; while i<length(orig) && not(design) i = i+1; if isa(orig{i},'mirdesign') design = i; end end end if design % For function with multiple inputs if design == 1 && not(get(orig{1},'Eval')) % Progressive construction of the general design [orig type] = init(orig,during); o = mirdesign(method,orig,during,after,specif,type); o = set(o,'Size',get(orig{1},'Size')); o = returndesign(o,nout); return else % Evaluation of the design. % First top-down initiation (evaleach), then bottom-up process. for io = 1:length(orig) if isa(orig{io},'mirdesign') o = evaleach(orig{io}); if iscell(o) o = o{:}; end orig{io} = o; end end end elseif not(isempty(init)) && not(isempty(during)) if isstruct(during) && isfield(during,'frame') && ... isstruct(during.frame) && during.frame.auto orig = mirframe(orig,during.frame.length,... during.frame.hop,... during.frame.phase); end % The input of the function is not a design flowchart, which % the 'init' part of the function could be integrated into. % (cf. previous call of 'init' in this script). % For that reason, the 'init' part of the function needs to be % evaluated now. orig = init(orig,during); end end % Performs the 'main' part of the MIRtoolbox function. if not(iscell(orig) && not(ischar(orig{1}))) && ... not(isa(orig,'mirdesign') || isa(orig,'mirdata')) o = {orig}; return end filenamearg = orig; if iscell(filenamearg) && not(ischar(filenamearg{1})) filenamearg = filenamearg{1}; end if iscell(filenamearg) && not(ischar(filenamearg{1})) filenamearg = filenamearg{1}; end filename = get(filenamearg,'Name'); if not(isempty(during)) && mirverbose if length(filename) == 1 disp(['Computing ',func2str(method),' related to ',filename{1},'...']) else disp(['Computing ',func2str(method),' for all audio files ...']) end end if iscell(x) x1 = x{1}; else x1 = x; end if not(iscell(orig) || isnumeric(x)) orig = set(orig,'Index',get(x1,'Index')); end if iscell(orig) o = main(orig,during,after); else d = get(orig,'Data'); if isamir(orig,'miraudio') && ... length(d) == 1 && length(d{1}) == 1 && isempty(d{1}{1}) % To solve a problem when MP3read returns empty chunk. % Warning: it should not be a cell, because for instance nthoutput can have first input empty... o = orig; else o = main(orig,during,after); end end if not(iscell(o) && length(o)>1) || (isa(x,'mirdesign') && get(x,'Eval')) o = {o x}; elseif iscell(x) && isa(x{1},'mirdesign') && get(x{1},'Eval') o = {o x}; elseif not(isempty(varg)) && isstruct(varg{1}) ... && not(iscell(o) && iscell(o{1})) % When the function was called by mireval, the output should be packed % into one single cell array (in order to be send back to calling % routines). o = {o}; end function o = returndesign(i,nout) o = cell(1,nout); o{1} = i; for k = 2:nout o{k} = nthoutput(i,k); end
github
martinarielhartmann/mirtooloct-master
mirframe.m
.m
mirtooloct-master/MIRToolbox/mirframe.m
13,483
utf_8
67e4955e693f53ac79b5e4520b3d7198
function [f x] = mirframe(x,varargin) % f = mirframe(x) creates the frame decomposition of the audio signal x. % (x can be a file name as well.) % Optional arguments: % mirframe(x,'Length',w,wu): % w is the length of the window in seconds (default: .05 seconds) % u is the unit, either % 's' (seconds, default unit) % or 'sp' (number of samples) % mirframe(x,'Hop',h,hu): % h is the hop factor, or distance between successive frames % (default: half overlapping: each frame begins at the middle % of the previous frame) % u is the unit, either % '/1' (ratio with respect to the frame length, default unit) % '%' (ratio as percentage) % 's' (seconds) % 'sp' (number of samples) % or 'Hz' (hertz), i.e., number of frames per second: the % exactness of the frame rate is ensured and may cause a % slight fluctuation of the elementary hop distances. % These arguments can also be written as follows: % mirframe(x,w,wu,h,hu) % (where some of these parameters can be omitted). if isempty(x) f = {}; return end if iscell(x) x = x{1}; end if nargin == 0 f = miraudio; elseif isa(x,'mirdesign') if not(get(x,'Eval')) % During bottom-up construction of the general design para = scanargin(varargin); type = get(x,'Type'); f = mirdesign(@mirframe,x,para,{},struct,type); fl = get(x,'FrameLength'); fh = get(x,'FrameHop'); fp = get(x,'FramePhase'); flu = get(x,'FrameLengthUnit'); fhu = get(x,'FrameHopUnit'); fpu = get(x,'FramePhaseUnit'); fpe = get(x,'FramePhaseAtEnd'); if fl f = set(f,'FrameLength',fl,'FrameLengthUnit',flu,... 'FrameHop',fh,'FrameHopUnit',fhu,... 'FramePhase',fp,'FramePhaseUnit',fpu,... 'FramePhaseAtEnd',fpe); else f = set(f,'FrameLength',para.wlength.val,... 'FrameLengthUnit',para.wlength.unit,... 'FrameHop',para.hop.val,... 'FrameHopUnit',para.hop.unit,... 'FramePhase',para.phase.val,... 'FramePhaseUnit',para.phase.unit,... 'FramePhaseAtEnd',fpe); end f = set(f,'FrameEval',1,... 'SeparateChannels',get(x,'SeparateChannels')); if not(isamir(x,'miraudio')) f = set(f,'NoChunk',1); end else % During top-down evaluation initiation if isstruct(varargin{1}) && isfield(varargin{1},'struct') tmp = varargin{1}.struct; x = set(x,'Struct',tmp); varargin{1} = rmfield(varargin{1},'struct'); end e = evaleach(x); if iscell(e) e = e{1}; end if isempty(mirgetdata(e)) f = e; else sc = get(x,'Scale'); if ~isempty(sc) varargin{1}.wlength.val = varargin{1}.wlength.val(sc); if length(varargin{1}.hop.val)>1 varargin{1}.hop.val = varargin{1}.hop.val(sc); end end if get(x,'ChunkDecomposed') varargin{1}.phase.val = 0; % The phase has already been taken into account in the % chunk decomposition. end f = mirframe(e,varargin{:}); end end elseif isa(x,'mirdata') if isframed(x) warning('WARNING IN MIRFRAME: The input data is already decomposed into frames. No more frame decomposition.'); f = x; else x = purgedata(x); dx = get(x,'Data'); if isa(x,'mirtemporal') dt = get(x,'Time'); else dt = get(x,'FramePos'); end sf = get(x,'Sampling'); para = scanargin(varargin); dx2 = cell(1,length(dx)); % magnitude in framed structure dt2 = cell(1,length(dx)); % time positions in framed structure fp = cell(1,length(dx)); % frame positions l2 = cell(1,length(dx)); fr = cell(1,length(dx)); for k = 1:length(dx) % For each audio file, ... dxk = dx{k}; dtk = dt{k}; if strcmpi(para.wlength.unit,'s') l = para.wlength.val*sf{k}; elseif strcmpi(para.wlength.unit,'sp') l = para.wlength.val; end if strcmpi(para.hop.unit,'/1') h = para.hop.val*l; fr{k} = sf{k}/h; elseif strcmpi(para.hop.unit,'%') h = para.hop.val*l*.01; fr{k} = sf{k}/h; elseif strcmpi(para.hop.unit,'s') h = para.hop.val*sf{k}; fr{k} = 1/para.hop.val; elseif strcmpi(para.hop.unit,'sp') h = para.hop.val; fr{k} = sf{k}/h; elseif strcmpi(para.hop.unit,'Hz') h = sf{k}/para.hop.val; fr{k} = para.hop.val; end if para.phase.atend p = mod(-l,h); else p = 0; end if strcmpi(para.phase.unit,'s') p = p + para.phase.val*sf{k}; elseif strcmpi(para.phase.unit,'sp') p = p + para.phase.val; elseif strcmpi(para.phase.unit,'/1') p = p + para.phase.val*h; elseif strcmpi(para.phase.unit,'%') p = p + para.phase.val*h*.01; end l = floor(l); dx2k = cell(1,length(dxk)); dt2k = cell(1,length(dxk)); fpk = cell(1,length(dxk)); l2k = cell(1,length(dxk)); if size(l)==1 for j = 1:length(dxk) % For each segment, ... dxj = dxk{j}; dtj = dtk{j}; if not(isa(x,'mirtemporal')) dxj = dxj'; dtj = dtj(1,:)'; end n = floor((size(dxj,1)-l-p)/h)+1; % Number of frames dx2j = zeros(l,n,size(dxj,3)); dt2j = zeros(l,n); fpj = zeros(2,n); if n < 1 disp('Frame length longer than total sequence size. No frame decomposition.'); dx2j = dxj(:,1,:); dt2j = dtj; if isempty(dtj) fpk = []; else fpj = [dtj(1) ; dtj(end)]; end else for i = 1:n % For each frame, ... st = floor((i-1)*h+p+1); stend = st+l-1; dx2j(:,i,:) = dxj(st:stend,1,:); dt2j(:,i) = dtj(st:stend); fpj(:,i) = [dtj(st) dtj(stend)]; end end dx2k{j} = dx2j; dt2k{j} = dt2j; fpk{j} = fpj; l2k{j} = l; end dx2{k} = dx2k; dt2{k} = dt2k; fp{k} = fpk; l2{k} = l2k; else % Multi-scale version if size(h) == 1 h = repmat(h,size(l)); end for j = 1:length(l) % For each scale, ... dxj = dxk{1}; dtj = dtk{1}; if not(isa(x,'mirtemporal')) dxj = dxj'; dtj = dtj(1,:)'; end n = floor((size(dxj,1)-l(j)-p)/h(j))+1; % Number of frames dx2j = zeros(l(j),n,size(dxj,3)); dt2j = zeros(l(j),n); fpj = zeros(2,n); if n < 1 disp('Frame length longer than total sequence size. No frame decomposition.'); dx2j = dxj(:,1,:); dt2j = dtj; fpj = [dtj(1) ; dtj(end)]; else for i = 1:n % For each frame, ... st = floor((i-1)*h(j)+p+1); stend = st+l(j)-1; dx2j(:,i,:) = dxj(st:stend,1,:); dt2j(:,i) = dtj(st:stend); fpj(:,i) = [dtj(st) dtj(stend)]; end end dx2k{j} = dx2j; dt2k{j} = dt2j; fpk{j} = fpj; l2k{j} = l(j); end dx2{k} = dx2k; dt2{k} = dt2k; fp{k} = fpk; l2{k} = l2k; end end if isa(x,'mirtemporal') f = set(x,'Time',dt2,'Data',dx2,... 'FramePos',fp,'FrameRate',fr,'Length',l2); else f = mirtemporal([],'Time',dt2,'Data',dx2,... 'FramePos',fp,'FrameRate',fr,... 'Sampling',get(x,'Sampling'),'Name',get(x,'Name'),... 'Label',get(x,'Label'),'Channels',get(x,'Channels'),... 'Centered',0,'Length',l2,'Title',get(x,'Title')); end end else f = mirframe(miraudio(x),varargin{:}); end function para = scanargin(v) if not(isempty(v)) && isstruct(v{1}) if length(v) == 1 para = v{1}; else para.wlength = v{1}; para.hop = v{2}; para.phase = v{3}; end return end para.wlength.val = 0.05; para.wlength.unit = 's'; para.hop.val = 0.5; para.hop.unit = '/1'; para.phase.val = 0; para.phase.unit = '/1'; para.phase.atend = 0; nv = length(v); i = 1; j = 1; while i <= nv arg = v{i}; if strcmpi(arg,'WinLength') || strcmpi(arg,'Length') if i < nv && isnumeric(v{i+1}) i = i+1; j = 0; para.wlength.val = v{i}; else error('ERROR IN MIRFRAME: Incorrect use of Length option. See help mirframe.'); end if i < nv && ischar(v{i+1}) && ... (strcmpi(v{i+1},'s') || strcmpi(v{i+1},'sp')) i = i+1; para.wlength.unit = v{i}; end elseif strcmpi(arg,'Hop') if i < nv && isnumeric(v{i+1}) i = i+1; j = 0; para.hop.val = v{i}; else error('ERROR IN MIRFRAME: Incorrect use of Hop option. See help mirframe.'); end if i < nv && ischar(v{i+1}) && ... (strcmpi(v{i+1},'%') || strcmpi(v{i+1},'/1') || ... strcmpi(v{i+1},'s') || strcmpi(v{i+1},'sp') || ... strcmpi(v{i+1},'Hz')) i = i+1; para.hop.unit = v{i}; end elseif strcmpi(arg,'Phase') if i < nv && isnumeric(v{i+1}) i = i+1; j = 0; para.phase.val = v{i}; else error('ERROR IN MIRFRAME: Incorrect use of Phase option. See help mirframe.'); end if i < nv && ischar(v{i+1}) && ... (strcmpi(v{i+1},'%') || strcmpi(v{i+1},'/1') || ... strcmpi(v{i+1},'s') || strcmpi(v{i+1},'sp')) i = i+1; para.phase.unit = v{i}; end if i < nv && ischar(v{i+1}) && strcmpi(v{i+1},'AtEnd') i = i+1; para.phase.atend = 'AtEnd'; end elseif isnumeric(arg) switch j case 1 j = 2; para.wlength.val = arg; if i < nv && ischar(v{i+1}) && ... (strcmpi(v{i+1},'s') || strcmpi(v{i+1},'sp')) i = i+1; para.wlength.unit = v{i}; end case 2 j = 3; para.hop.val = arg; if i < nv && ischar(v{i+1}) && ... (strcmpi(v{i+1},'%') || strcmpi(v{i+1},'/1') || ... strcmpi(v{i+1},'s') || strcmpi(v{i+1},'sp') || ... strcmpi(v{i+1},'Hz')) i = i+1; para.hop.unit = v{i}; end case 3 j = 4; para.phase.val = arg; if i < nv && ischar(v{i+1}) && ... (strcmpi(v{i+1},'%') || strcmpi(v{i+1},'/1') || ... strcmpi(v{i+1},'s') || strcmpi(v{i+1},'sp')) i = i+1; para.phase.unit = v{i}; end if i < nv && ischar(v{i+1}) && strcmpi(v{i+1},'AtEnd') i = i+1; para.phase.atend = 'AtEnd'; elseif i < nv && isnumeric(v{i+1}) && ~v{i+1} i = i+1; para.phase.atend = 0; end otherwise error('ERROR IN MIRFRAME: Syntax error. See help mirframe.'); end elseif not(isempty(arg)) error('ERROR IN MIRFRAME: Syntax error. See help mirframe.'); end i = i+1; end
github
martinarielhartmann/mirtooloct-master
mirexport.m
.m
mirtooloct-master/MIRToolbox/mirexport.m
11,415
utf_8
cd8a7963e667f6bc41be6b8f306c8882
function m = mirexport(f,varargin) % mirexport(filename,...) exports statistical information related to % diverse data into a text file called filename. % mirexport('Workspace',...) instead directly output the statistical % information in a structure array saved in the Matlab workspace. % This structure contains three fields: % filenames: the name of the original audio files, % types: the name of the features, % data: the data. % The exported data should be related to the same initial audio file % or the same ordered set of audio files. % The data listed after the first arguments can be: % - any feature computed in MIRtoolbox. % What will be exported is the statistical description of the % feature (using the mirstat function) % - any structure array of such features. % Such as the ouput of the mirstat function. % - any cell array of such features. % - the name of a text file. % The text file is imported with the Matlab importdata command. % Each line of the file should contains a fixed number of data % delimited by tabulations. The first line, or 'header', % indicates the name of each of these columns. % The file format of the output can be either: % - a text file. % It follows the same text file representation as for the input % text files. The first column of the matrix indicates the name % of the audio files. The text file can be opened in Matlab, % or in a spreadsheet program, such as Microsoft Excel, where the % data matrix can be automatically reconstructed. % - an attribute-relation file. % It follows the ARFF standard, used in particular in the WEKA % data mining environment. stored.data = {}; stored.textdata = {}; stored.name = {}; narg = nargin; if strcmpi(f,'Workspace') format = 'Workspace'; elseif length(f)>4 && strcmpi(f(end-4:end),'.arff') format = 'ARFF'; else format = 'Matrix'; end v = ver('MIRtoolbox'); title = ['MIRtoolbox' v.Version]; class = {}; add = 0; raw = 0; for v = 2:narg argv = varargin{v-1}; if isa(argv,'mirdesign') mirerror('MIREXPORT','You can only export features that have been already evaluated (using mireval).'); end if ischar(argv) if strcmpi(argv,'Matrix') format = 'Matrix'; elseif strcmpi(argv,'ARFF') format = 'ARFF'; elseif strcmpi(argv,'#add') add = 1; elseif strcmpi(argv,'Raw') raw = 1; end end end for v = 2:narg argv = varargin{v-1}; if ischar(argv) if ~strcmpi(argv,'Matrix') && ~strcmpi(argv,'ARFF') && ... ~strcmpi(argv,'#add') && ~strcmpi(argv,'Raw') imported = importdata(argv,'\t',1); imported.name = {}; [stored class] = integrate(stored,imported,raw); end elseif isstruct(argv) && isfield(argv,'data') new.data = argv.data; new.textdata = argv.fields; new.name = {}; [stored class] = integrate(stored,new,raw); else new.data = argv; new.textdata = ''; new.name = {}; [stored class] = integrate(stored,new,raw); end end switch format case 'Matrix' matrixformat(stored,f,title,add,raw); m = 1; case 'ARFF' classes = {}; for i = 1:length(class) if isempty(strcmp(class{i},classes)) || not(max(strcmp(class{i},classes))) classes{end+1} = class{i}; end end ARFFformat(stored,f,title,class,classes,add); m = 1; case 'Workspace' m = variableformat(stored,f,title); end %% function [stored class] = integrate(stored,new,raw,class) if nargin<4 class = {}; end % Input information data = new.data; textdata = new.textdata; if isfield(new,'name') name = new.name; else name = {}; end % Input information after processing newdata = {}; newtextdata = {}; newname = {}; if isstruct(data) if isfield(data,'Class') class = data.Class; data = rmfield(data,'Class'); end if isfield(data,'FileNames') name = data.FileNames; data = rmfield(data,'FileNames'); end fields = fieldnames(data); nfields = length(fields); for w = 1:nfields % Field information field = fields{w}; newfield.data = data.(field); if isempty(textdata) newfield.textdata = field; else newfield.textdata = strcat(textdata,'_',field); end % Processing of the field [n class] = integrate({},newfield,raw,class); % Concatenation of the results newdata = {newdata{:} n.data{:}}; newtextdata = {newtextdata{:} n.textdata{:}}; newname = checkname(newname,name); end elseif isa(data,'mirdata') if raw newinput.data = mirgetdata(data); else newinput.data = mirstat(data); end if isfield(newinput.data,'FileNames') newinput.data = rmfield(newinput.data,'FileNames'); end title = get(data,'Title'); newinput.textdata = [textdata '_' title(find(not(isspace(title))))]; [n class] = integrate({},newinput,raw,class); newdata = n.data; newtextdata = n.textdata; newname = get(data,'Name'); elseif iscell(textdata) % Input comes from importdata nvar = size(data,2); newdata = cell(1,nvar); newtextdata = cell(1,nvar); for i = 1:nvar newdata{i} = data(:,i); newtextdata{i} = textdata{i}; end newname = {}; elseif iscell(data) for i = 1:length(data) if not(isempty(data{i})) % Element information newelement.data = data{i}; newelement.textdata = [textdata num2str(i)]; % Processing of the element [n class] = integrate({},newelement,raw,class); % Concatenation of the results newdata = {newdata{:} n.data{:}}; newtextdata = {newtextdata{:} n.textdata{:}}; newname = checkname(newname,n.name); end end elseif size(data,4)>1 % Input is vector for w = 1:size(data,4) % Bin information bin.data = data(:,:,:,w); if isempty(textdata) bin.textdata = num2str(w); else bin.textdata = strcat(textdata,'_',num2str(w)); end % Processing of the bin [n class] = integrate({},bin,raw,class); % Concatenation of the results newdata = {newdata{:} n.data{:}}; newtextdata = {newtextdata{:} n.textdata{:}}; end elseif size(data,3)>1 % Input is vector for w = 1:size(data,3) % Bin information bin.data = data(:,:,w,:); if isempty(textdata) bin.textdata = num2str(w); else bin.textdata = strcat(textdata,'_',num2str(w)); end % Processing of the bin [n class] = integrate({},bin,raw,class); % Concatenation of the results newdata = {newdata{:} n.data{:}}; newtextdata = {newtextdata{:} n.textdata{:}}; end elseif size(data,1)>1 && size(data,1)<=50 % Input is vector for w = 1:size(data,1) % Bin information bin.data = data(w,:,:,:); if isempty(textdata) bin.textdata = num2str(w); else bin.textdata = strcat(textdata,'_',num2str(w)); end % Processing of the bin [n class] = integrate({},bin,raw,class); % Concatenation of the results newdata = {newdata{:} n.data{:}}; newtextdata = {newtextdata{:} n.textdata{:}}; end else if size(data,1)>1 data = mean(data); end newdata = {data}; newtextdata = {textdata}; newname = {}; end if isempty(stored) stored.data = newdata; stored.textdata = newtextdata; stored.name = newname; else stored.data = {stored.data{:} newdata{:}}; stored.textdata = {stored.textdata{:} newtextdata{:}}; if isempty(stored.name) stored.name = newname; else stored.name = checkname(newname,stored.name); end end function m = matrixformat(data,filename,title,add,raw) named = ~isempty(data.name); if raw rawl = 0; for i = 1:length(data.data) rawl = max(rawl,length(data.data{i})); end end if named && ~raw if not(add) m(1,:) = {title,data.textdata{:}}; end for i = 1:length(data.name) m{i+~add,1} = data.name{i}; end elseif not(add) m(1,:) = {data.textdata{:}}; end for i = 1:length(data.data) m((1:length(data.data{i}))+~add,i+named) = num2cell(data.data{i}); if raw for j =length(data.data{i})+1:rawl m{j+~add,i+named} = NaN; end end end if add fid = fopen(filename,'at'); else fid = fopen(filename,'wt'); end for i = 1:size(m,1) for j = 1:size(m,2) if ischar(m{i,j}) fprintf(fid,'%s\t', m{i,j}(find(not(m{i,j} == ' ')))); else if iscell(m{i,j}) % Problem with key strength pos to be solved fprintf(fid,'%f\t', m{i,j}{1}); else fprintf(fid,'%f\t', m{i,j}); end end end fprintf(fid,'\n'); end fclose(fid); disp(['Data exported to file ',filename,'.']); function ARFFformat(data,filename,title,class,classes,add) if add fid = fopen(filename,'at'); else fid = fopen(filename,'wt'); fprintf(fid,['%% Attribution-Relation File automatically generated using ',title,'\n\n']); fprintf(fid,'@RELATION %s\n\n',title); for i = 1:length(data.textdata) fprintf(fid,'@ATTRIBUTE %s NUMERIC\n',data.textdata{i}); end if not(isempty(class)) fprintf(fid,'@ATTRIBUTE class {'); for i = 1:length(classes) if i>1 fprintf(fid,','); end fprintf(fid,'%s',classes{i}); end fprintf(fid,'}\n'); end fprintf(fid,'\n@DATA\n'); fid2 = fopen([filename(1:end-5) '.filenames.txt'],'wt'); for i = 1:length(data.name) fprintf(fid2,'%s\n',data.name{i}); end fclose(fid2); end try data = cell2mat(data.data(:))'; catch error('ERROR IN MIREXPORT: Are you sure all the data to be exported relate to the same ordered list of audio files?'); end for i = 1:size(data,1) fprintf(fid,'%d ',data(i,:)); if not(isempty(class)) fprintf(fid,'%s',class{i}); end fprintf(fid,'\n'); end fclose(fid); disp(['Data exported to file ',filename,'.']); function m = variableformat(data,filename,title) m.types = data.textdata; m.filenames = data.name; for i = 1:length(data.data) m.data{i} = data.data{i}; end function name = checkname(newname,name) if not(isempty(newname)) && not(isempty(name)) if length(newname) == length(name) for i = 1:length(name) if not(strcmp(name{i},newname{i})) error('ERROR IN MIREXPORT: All the input are not associated to the same audio files (or the same ordering of these files.'); end end else error('ERROR IN MIREXPORT: All the input are not associated to the same audio files.'); end elseif isempty(name) name = newname; end
github
martinarielhartmann/mirtooloct-master
mirrms.m
.m
mirtooloct-master/MIRToolbox/mirrms.m
1,741
utf_8
6e4442b73eeb6ed66bad3386b9f1059a
function varargout = mirrms(x,varargin) % e = mirrms(x) calculates the root mean square energy. % Optional arguments: % mirrms(...,'Frame') computes the temporal evolution of the energy. notchunking.type = 'Boolean'; notchunking.when = 'After'; notchunking.default = 1; option.notchunking = notchunking; median.key = 'Median'; median.type = 'Boolean'; median.default = 0; option.median = median; warning.key = 'Warning'; warning.type = 'Boolean'; warning.default = 1; option.warning = warning; specif.option = option; specif.defaultframelength = 0.05; specif.defaultframehop = 0.5; specif.combinechunk = 'Sum'; varargout = mirfunction(@mirrms,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'mirscalar'; function x = main(x,option,postoption) if iscell(x) x = x{1}; end if ~isempty(option) && option.median method = @median; else method = @mean; end if ~isamir(x,'mirscalar') if option.warning && ~isamir(x,'miraudio') warning(['Do you really intend to apply MIRRMS on a ',class(x),'?']); end d = get(x,'Data'); v = mircompute(@algo,d,method); x = mirscalar(x,'Data',v,'Title','RMS energy'); end if isstruct(postoption) && isfield(postoption,'notchunking') ... && postoption.notchunking x = after(x); end function e = algo(d,method) nc = size(d,2); nch = size(d,3); e = zeros(1,nc,nch); for i = 1:nch for j = 1:nc dj = d(:,j,i).^2; e(1,j,i) = method(dj); end end function x = after(x) v = mircompute(@afternorm,get(x,'Data'),get(x,'Length')); x = set(x,'Data',v); function d = afternorm(d,l) d = sqrt(d);
github
martinarielhartmann/mirtooloct-master
mirpulseclarity.m
.m
mirtooloct-master/MIRToolbox/mirpulseclarity.m
14,197
utf_8
73a2c53e476d619b3a505e7bb4bf038b
function varargout = mirpulseclarity(orig,varargin) % r = mirpulseclarity(x) estimates the rhythmic clarity, indicating the % strength of the beats estimated by the mirtempo function. % Optional arguments: % mirpulseclarity(...,s): specifies a strategy for pulse clarity % estimation. % Possible values: 'MaxAutocor' (default), 'MinAutocor', % 'KurtosisAutocor', MeanPeaksAutocor', 'EntropyAutocor', % 'InterfAutocor', 'TempoAutocor', 'ExtremEnvelop', % 'Attack', 'Articulation' % mirpulseclarity(...,'Frame',l,h): orders a frame decomposition of % the audio input of window length l (in seconds) and hop factor % h, expressed relatively to the window length. % Default values: l = 5 seconds and h = .1 % Onset detection strategies: 'Envelope' (default), 'DiffEnvelope', % 'SpectralFlux', 'Pitch'. % Options related to the autocorrelation computation can be specified % as well: 'Min', 'Max', 'Resonance', 'Enhanced' % Options related to the tempo estimation can be specified here % as well: 'Sum', 'Total', 'Contrast'. % cf. User's Manual for more details. % [r,a] = mirpulseclarity(x) also returns the beat autocorrelation. model.key = 'Model'; model.type = 'Integer'; model.default = 0; option.model = model; stratg.type = 'String'; stratg.choice = {'MaxAutocor','MinAutocor','MeanPeaksAutocor',... 'KurtosisAutocor','EntropyAutocor',... 'InterfAutocor','TempoAutocor','ExtremEnvelop',... 'Attack','Articulation'}; ...,'AttackDiff' stratg.default = 'MaxAutocor'; option.stratg = stratg; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.keydefault = [5 .1]; frame.default = [0 0]; option.frame = frame; %% options related to mironsets: fea.type = 'String'; fea.choice = {'Envelope','DiffEnvelope','SpectralFlux','Pitch'}; fea.default = 'Envelope'; option.fea = fea; %% options related to 'Envelope': envmeth.key = 'Method'; envmeth.type = 'String'; envmeth.choice = {'Filter','Spectro'}; envmeth.default = 'Spectro'; option.envmeth = envmeth; %% options related to 'Filter': ftype.key = 'FilterType'; ftype.type = 'String'; ftype.choice = {'IIR','HalfHann'}; ftype.default = 'IIR'; option.ftype = ftype; fb.key = 'Filterbank'; fb.type = 'Integer'; fb.default = 20; option.fb = fb; fbtype.key = 'FilterbankType'; fbtype.type = 'String'; fbtype.choice = {'Gammatone','Scheirer','Klapuri'}; fbtype.default = 'Scheirer'; option.fbtype = fbtype; %% options related to 'Spectro': band.type = 'String'; band.choice = {'Freq','Mel','Bark','Cents'}; band.default = 'Freq'; option.band = band; diffhwr.key = 'HalfwaveDiff'; diffhwr.type = 'Integer'; diffhwr.default = 0; diffhwr.keydefault = 1; option.diffhwr = diffhwr; lambda.key = 'Lambda'; lambda.type = 'Integer'; lambda.default = 1; option.lambda = lambda; aver.key = 'Smooth'; aver.type = 'Integer'; aver.default = 0; aver.keydefault = 30; option.aver = aver; oplog.key = 'Log'; oplog.type = 'Boolean'; oplog.default = 0; option.log = oplog; mu.key = 'Mu'; mu.type = 'Integer'; mu.default = 100; option.mu = mu; %% options related to 'SpectralFlux' inc.key = 'Inc'; inc.type = 'Boolean'; inc.default = 1; option.inc = inc; median.key = 'Median'; median.type = 'Integer'; median.number = 2; median.default = [0 0]; % Not same default as in mirtempo option.median = median; hw.key = 'Halfwave'; hw.type = 'Boolean'; hw.default = 0; %NaN; %0; % Not same default as in mirtempo option.hw = hw; %% options related to mirattackslope slope.type = 'String'; slope.choice = {'Diff','Gauss'}; slope.default = 'Diff'; option.slope = slope; %% options related to mirautocor: enh.key = 'Enhanced'; enh.type = 'Integers'; enh.default = []; enh.keydefault = 2:10; option.enh = enh; r.key = 'Resonance'; r.type = 'String'; r.choice = {'ToiviainenSnyder','vonNoorden',0,'off','no'}; r.default = 'ToiviainenSnyder'; option.r = r; mi.key = 'Min'; mi.type = 'Integer'; mi.default = 40; option.mi = mi; ma.key = 'Max'; ma.type = 'Integer'; ma.default = 200; option.ma = ma; %% options related to mirtempo: sum.key = 'Sum'; sum.type = 'String'; sum.choice = {'Before','After','Adjacent'}; sum.default = 'Before'; option.sum = sum; m.key = 'Total'; m.type = 'Integer'; m.default = 1; option.m = m; thr.key = 'Contrast'; thr.type = 'Integer'; thr.default = 0.01; % Not same default as in mirtempo option.thr = thr; specif.option = option; varargout = mirfunction(@mirpulseclarity,orig,varargin,nargout,specif,@init,@main); %% Initialisation function [x type] = init(x,option) %if isframed(x) % warning('WARNING IN MIRPULSECLARITY: The input should not be already decomposed into frames.'); % disp(['Suggestion: Use the ''Frame'' option instead.']) %end if iscell(x) x = x{1}; end if isamir(x,'mirautocor') type = {'mirscalar','mirautocor'}; elseif length(option.model) > 1 a = x; type = {'mirscalar'}; for m = 1:length(option.model) if option.frame.length.val y = mirpulseclarity(a,'Model',option.model(m),... 'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit); else y = mirpulseclarity(a,'Model',option.model(m)); end if m == 1 x = y; else x = x + y; end end else if option.model switch option.model case 1 case 2 option.envmeth = 'Filter'; option.fbtype = 'Gammatone'; option.mu = 0; option.r = 0; option.lambda = .8; option.sum = 'After'; end end if length(option.stratg)>7 && strcmpi(option.stratg(end-6:end),'Autocor') if (strcmpi(option.stratg,'MaxAutocor') || ... strcmpi(option.stratg,'MinAutocor') || ... strcmpi(option.stratg,'EntropyAutocor')) option.m = 0; end if strcmpi(option.stratg,'MinAutocor') option.enh = 0; end if option.frame.length.val [t,x] = mirtempo(x,option.fea,'Method',option.envmeth,... option.band,... 'Sum',option.sum,'Enhanced',option.enh,... 'Resonance',option.r,'Smooth',option.aver,... 'HalfwaveDiff',option.diffhwr,... 'Lambda',option.lambda,... 'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... 'FilterbankType',option.fbtype,... 'FilterType',option.ftype,... 'Filterbank',option.fb,'Mu',option.mu,... 'Log',option.log,... 'Inc',option.inc,'Halfwave',option.hw,... 'Median',option.median(1),option.median(2),... 'Min',option.mi,'Max',option.ma,... 'Total',option.m,'Contrast',option.thr); else [t,x] = mirtempo(x,option.fea,'Method',option.envmeth,... option.band,... 'Sum',option.sum,'Enhanced',option.enh,... 'Resonance',option.r,'Smooth',option.aver,... 'HalfwaveDiff',option.diffhwr,... 'Lambda',option.lambda,... 'FilterbankType',option.fbtype,... 'FilterType',option.ftype,... 'Filterbank',option.fb,'Mu',option.mu,... 'Log',option.log,... 'Inc',option.inc,'Halfwave',option.hw,... 'Median',option.median(1),option.median(2),... 'Min',option.mi,'Max',option.ma,... 'Total',option.m,'Contrast',option.thr); end type = {'mirscalar','mirautocor'}; elseif strcmpi(option.stratg,'ExtremEnvelop') x = mironsets(x,'Filterbank',option.fb); type = {'mirscalar','mirenvelope'}; elseif strcmpi(option.stratg,'Attack') x = mirattackslope(x,option.slope); type = {'mirscalar','mirenvelope'}; % elseif strcmpi(option.stratg,'AttackDiff') % type = {'mirscalar','mirenvelope'}; elseif strcmpi(option.stratg,'Articulation') x = mirlowenergy(x,'ASR'); type = {'mirscalar','mirscalar'}; else type = {'mirscalar','miraudio'}; end end %% Main function function o = main(a,option,postoption) if option.model == 2 option.stratg = 'InterfAutocor'; end if isa(a,'mirscalar') && not(strcmpi(option.stratg,'Attack')) % not very nice test... to improve. o = {a}; return end if option.m == 1 && ... (strcmpi(option.stratg,'InterfAutocor') || ... strcmpi(option.stratg,'MeanPeaksAutocor')) option.m = Inf; end if iscell(a) a = a{1}; end if strcmpi(option.stratg,'MaxAutocor') d = get(a,'Data'); rc = mircompute(@max,d); elseif strcmpi(option.stratg,'MinAutocor') d = get(a,'Data'); rc = mircompute(@minusmin,d); elseif strcmpi(option.stratg,'MeanPeaksAutocor') m = get(a,'PeakVal'); rc = mircompute(@meanpeaks,m); elseif strcmpi(option.stratg,'KurtosisAutocor') a = mirpeaks(a,'Extract','Total',option.m,'NoBegin','NoEnd'); k = mirkurtosis(a); %d = get(k,'Data'); %rc = mircompute(@meanpeaks,d); rc = mirmean(k); elseif strcmpi(option.stratg,'EntropyAutocor') rc = mirentropy(a); elseif strcmpi(option.stratg,'InterfAutocor') a = mirpeaks(a,'Total',option.m,'NoBegin','NoEnd'); m = get(a,'PeakVal'); p = get(a,'PeakPosUnit'); rc = mircompute(@interf,m,p); elseif strcmpi(option.stratg,'TempoAutocor') a = mirpeaks(a,'Total',1,'NoBegin','NoEnd'); p = get(a,'PeakPosUnit'); rc = mircompute(@tempo,p); elseif strcmpi(option.stratg,'ExtremEnvelop') a = mirenvelope(a,'Normal'); p = mirpeaks(a,'Order','Abscissa'); p = get(p,'PeakPreciseVal'); n = mirpeaks(a,'Valleys','Order','Abscissa'); n = get(n,'PeakPreciseVal'); rc = mircompute(@shape,p,n); elseif strcmpi(option.stratg,'Attack') rc = mirmean(a); %elseif strcmpi(option.stratg,'AttackDiff') % a = mirpeaks(a); % m = get(a,'PeakVal'); % rc = mircompute(@meanpeaks,m); elseif strcmpi(option.stratg,'Articulation') rc = a; end if iscell(rc) pc = mirscalar(a,'Data',rc,'Title','Pulse clarity'); else pc = set(rc,'Title',['Pulse clarity (',get(rc,'Title'),')']); end if option.model switch option.model case 1 alpha = 0; beta = 2.2015; lambda = .1; case 2 alpha = 0; beta = 3.5982; lambda = 1.87; end if not(lambda == 0) pc = (pc+alpha)^lambda * beta; else pc = log(pc+alpha) * beta; end title = ['Pulse clarity (Model ',num2str(option.model),')']; pc = set(pc,'Title',title); end o = {pc a}; %% Routines function r = shape(p,n) p = p{1}; n = n{1}; if length(p)>length(n) d = sum(p(1:end-1) - n) + sum(p(2:end) - n); r = d/(2*length(n)); elseif length(p)<length(n) d = sum(p - n(1:end-1)) + sum(p - n(2:end)); r = d/(2*length(p)); else d = sum(p(2:end) - n(1:end-1)) + sum(p(1:end-1) - n(2:end)); r = d/(2*(length(p)-1)); end function rc = minusmin(ac) rc = -min(ac); function rc = meanpeaks(ac) rc = zeros(1,length(ac)); for j = 1:length(ac) if isempty(ac{j}) rc(j) = NaN; else rc(j) = mean(ac{j}); end end function rc = interf(mk,pk) rc = zeros(size(mk)); for j = 1:size(mk,3) for i = 1:size(mk,2) pij = pk{1,i,j}; mij = mk{1,i,j}; if isempty(pij) rc(1,i,j) = 0; else high = max(pij(2:end),pij(1)); low = min(pij(2:end),pij(1)); quo = rem(high,low)./low; nomult = quo>.15 & quo<.85; fij = mij(2:end)/mij(1) .*nomult; fij(fij<0) = 0; rc(1,i,j) = exp(-sum(fij)/4); % Pulsations that are not in integer ratio % with dominant pulse decrease clarity end end end function rc = tempo(pk) rc = zeros(size(pk)); for j = 1:size(pk,3) for i = 1:size(pk,2) pij = pk{1,i,j}; if isempty(pij) rc(1,i,j) = 0; else rc(1,i,j) = exp(-pij(1)/4)/exp(-.33/4); % Fast dominant pulse % increases clarity end end end
github
martinarielhartmann/mirtooloct-master
mirflatness.m
.m
mirtooloct-master/MIRToolbox/mirflatness.m
2,139
utf_8
afd526e25826dda99d62b918bd5d0a27
function varargout = mirflatness(orig,varargin) % f = mirflatness(x) calculates the flatness of x, which can be either: % - a spectrum (spectral flatness), % - an envelope (temporal flatness), or % - any histogram. minrms.key = 'MinRMS'; minrms.when = 'After'; minrms.type = 'Numerical'; minrms.default = .01; option.minrms = minrms; specif.option = option; varargout = mirfunction(@mirflatness,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirenvelope') || isamir(x,'mirhisto')) x = mirspectrum(x); end type = 'mirscalar'; function f = main(x,option,postoption) if iscell(x) x = x{1}; end m = get(x,'Data'); y = cell(1,length(m)); for h = 1:length(m) if not(iscell(m{h})) % for histograms m{h} = {m{h}'}; end y{h} = cell(1,length(m{h})); for i = 1:length(m{h}) mm = m{h}{i}; nl = size(mm,1); ari = mean(mm); geo = (prod(mm.^(1/nl))); divideByZero = warning('query','MATLAB:divideByZero'); logZero = warning('query','MATLAB:log:logOfZero'); warning('off','MATLAB:divideByZero'); warning('off','MATLAB:log:logOfZero'); y{h}{i} = ...10*log10( geo./ari;%); warning(divideByZero.state,'MATLAB:divideByZero'); warning(logZero.state,'MATLAB:log:logOfZero'); nany = find(isinf(y{h}{i})); y{h}{i}(nany) = zeros(size(nany)); end end if isa(x,'mirenvelope') t = 'Temporal flatness'; elseif isa(x,'mirspectrum') t = 'Spectral flatness'; else t = ['Flatness of ',get(x,'Title')]; end f = mirscalar(x,'Data',y,'Title',t,'Unit',''); if isstruct(postoption) && strcmpi(get(x,'Title'),'Spectrum') && ... isfield(postoption,'minrms') && postoption.minrms f = after(x,f,postoption.minrms); end function f = after(x,f,minrms) r = mirrms(x,'Warning',0); v = mircompute(@trim,get(f,'Data'),get(r,'Data'),minrms); f = set(f,'Data',v); function d = trim(d,r,minrms) r = r/max(max(r)); pos = find(r<minrms); for i = 1:length(pos) d(pos(i)) = NaN; end d = {d};
github
martinarielhartmann/mirtooloct-master
mirhcdf.m
.m
mirtooloct-master/MIRToolbox/mirhcdf.m
756
utf_8
83f037cac2a2562fb1a64b60f5826078
function varargout = mirhcdf(orig,varargin) % df = mirhcdf(x) calculates the Harmonic Change Detection Function % related to x. % % C. A. Harte and M. B. Sandler, Detecting harmonic change in musical % audio, in Proceedings of Audio and Music Computing for Multimedia % Workshop, Santa Barbara, CA, 2006. specif.defaultframelength = .743; specif.defaultframehop = .1; varargout = mirfunction(@mirhcdf,orig,varargin,nargout,specif,@init,@main); function [df type] = init(orig,option) if isamir(orig,'mirscalar') df = orig; else if isframed(orig) tc = mirtonalcentroid(orig); else tc = mirtonalcentroid(orig,'Frame'); end df = mirflux(tc); end type = 'mirscalar'; function df = main(df,option,postoption)
github
martinarielhartmann/mirtooloct-master
mirrolloff.m
.m
mirtooloct-master/MIRToolbox/mirrolloff.m
2,405
utf_8
969a183f15d02c00dfb987d1237ec4b9
function varargout = mirrolloff(x,varargin) % r = mirrolloff(s) calculates the spectral roll-off in Hz. % Optional arguments: % r = mirrolloff(s,'Threshold',p) specifies the energy threshold in % percentage. (Default: .85) % p can be either a value between 0 and 1. But if p exceeds 1, it % is understood as a percentage, i.e. between 1 and 100. % In other words, r is the frequency under which p percents % of the spectral energy is distributed. % % Typical values for the energy threshold: % 85% in G. Tzanetakis, P. Cook. Musical genre classification of audio % signals. IEEE Tr. Speech and Audio Processing, 10(5),293-302, 2002. % 95% in T. Pohle, E. Pampalk, G. Widmer. Evaluation of Frequently % Used Audio Features for Classification of Music Into Perceptual % Categories, ? p.key = 'Threshold'; p.type = 'Integer'; p.default = 85; option.p = p; minrms.key = 'MinRMS'; minrms.when = 'After'; minrms.type = 'Numerical'; minrms.default = .005; option.minrms = minrms; specif.option = option; varargout = mirfunction(@mirrolloff,x,varargin,nargout,specif,@init,@main); function [s type] = init(x,option) s = mirspectrum(x); type = 'mirscalar'; function r = main(s,option,postoption) if iscell(s) s = s{1}; end m = get(s,'Magnitude'); f = get(s,'Frequency'); if option.p>1 option.p = option.p/100; end v = mircompute(@algo,m,f,option.p); r = mirscalar(s,'Data',v,'Title','Rolloff','Unit','Hz.'); if isstruct(postoption) r = after(s,r,postoption.minrms); end function v = algo(m,f,p) cs = cumsum(m); % accumulation of spectrum energy thr = cs(end,:,:)*p; % threshold corresponding to the rolloff point v = zeros(1,size(cs,2),size(cs,3)); for l = 1:size(cs,3) for k = 1:size(cs,2) fthr = find(cs(:,k,l) >= thr(1,k,l),1); % find the location of the threshold if isempty(fthr) v(1,k,l) = NaN; else v(1,k,l) = f(fthr); end end end function r = after(s,r,minrms) v = get(r,'Data'); if minrms rms = mirrms(s,'Warning',0); v = mircompute(@trimrms,v,get(rms,'Data'),minrms); end r = set(r,'Data',v); function d = trimrms(d,r,minrms) r = r/max(max(r)); pos = find(r<minrms); for i = 1:length(pos) d(pos(i)) = NaN; end d = {d};
github
martinarielhartmann/mirtooloct-master
mp3write.m
.m
mirtooloct-master/MIRToolbox/mp3write.m
4,870
utf_8
ed9f8770422e95bc286ccb1f58acfe92
function mp3write(D,SR,NBITS,FILE,OPTIONS) % MP3WRITE Write MP3 file by use of external binary % MP3WRITE(Y,FS,NBITS,FILE) writes waveform data Y to mp3-encoded % file FILE at sampling rate FS using bitdepth NBITS. % The syntax exactly mirrors WAVWRITE. NBITS must be 16. % MP3WRITE(Y,FS,FILE) assumes NBITS is 16 % MP3WRITE(Y,FILE) further assumes FS = 8000. % % MP3WRITE(..., OPTIONS) specifies additional compression control % options as a string passed directly to the lame encoder % program; default is '--quiet -h' for high-quality model. % % Example: % To convert a wav file to mp3 (assuming the sample rate is % supported): % [Y,FS] = wavread('piano.wav'); % mp3write(Y,FS,'piano.mp3'); % To force lame to use 160 kbps (instead of default 128 kbps) % with the default filename extension (mp3): % mp3write(Y,FS,'piano','--quiet -h -b 160'); % % Note: The actual mp3 encoding is done by an external binary, % lame, which is available for multiple platforms. Usable % binaries are available from: % http://labrosa.ee.columbia.edu/matlab/mp3read.html % % Note: MP3WRITE will use the mex file popenw, if available, to % open a pipe to the lame encoder. Otherwise, it will have to % write a large temporary file, then execute lame on that file. % popenw is available at: % http://labrosa.ee.columbia.edu/matlab/popenrw.html % This is a nice way to save large audio files as the % incremental output of your code, but you'll have to adapt the % central loop of this function (rather than using it directly). % % See also: mp3read, wavwrite, popenw. % 2005-11-10 Original version % 2007-02-04 Modified to exactly match wavwrite syntax, and to % automatically find architecture-dependent binaries. % 2007-07-26 Writing of stereo files via tmp file fixed (thx Yu-ching Lin) % % $Header: /Users/dpwe/matlab/columbiafns/RCS/mp3write.m,v 1.2 2007/07/26 15:09:16 dpwe Exp $ % find our baseline directory [path] = fileparts(which('mp3write')); % %%%%% Directory for temporary file (if needed) % % Try to read from environment, or use /tmp if it exists, or use CWD tmpdir = getenv('TMPDIR'); if isempty(tmpdir) || exist(tmpdir,'file')==0 tmpdir = '/tmp'; end if exist(tmpdir,'file')==0 tmpdir = ''; end % ensure it exists %if length(tmpdir) > 0 && exist(tmpdir,'file')==0 % mkdir(tmpdir); %end %%%%%% Command to delete temporary file (if needed) rmcmd = 'rm'; %%%%%% Location of the binary - attempt to choose automatically %%%%%% (or edit to be hard-coded for your installation) ext = lower(computer); if ispc ext = 'exe'; rmcmd = 'del'; end lame = fullfile(path,['lame.',ext]); %%%% Process input arguments % Do we have NBITS? mynargin = nargin; if ischar(NBITS) % NBITS is a string i.e. it's actually the filename if mynargin > 3 OPTIONS = FILE; end FILE = NBITS; NBITS = 16; % it's as if NBITS had been specified... mynargin = mynargin + 1; end if mynargin < 5 OPTIONS = '--quiet -h'; % -h means high-quality psych model end [nr, nc] = size(D); if nc < nr D = D'; [nr, nc] = size(D); end % Now rows are channels, cols are time frames (so interleaving is right) %%%%% add extension if none (like wavread) [path,file,ext] = fileparts(FILE); if isempty(ext) FILE = [FILE, '.mp3']; end nchan = nr; nfrm = nc; if nchan == 1 monostring = ' -m m'; else monostring = ''; end lameopts = [' ', OPTIONS, monostring, ' ']; %if exist('popenw') == 3 if length(which('popenw')) > 0 % We have the writable stream process extensions cmd = ['"',lame,'"', lameopts, '-r -s ',num2str(SR),' - "',FILE,'"']; p = popenw(cmd); if p < 0 error(['Error running popen(',cmd,')']); end % We feed the audio to the encoder in blocks of <blksize> frames. % By adapting this loop, you can create your own code to % write a single, large, MP3 file one part at a time. blksiz = 10000; nrem = nfrm; base = 0; while nrem > 0 thistime = min(nrem, blksiz); done = popenw(p,32767*D(:,base+(1:thistime)),'int16be'); nrem = nrem - thistime; base = base + thistime; %disp(['done=',num2str(done)]); end % Close pipe popenw(p,[]); else disp('Warning: popenw not available, writing temporary file'); tmpfile = fullfile(tmpdir,['tmp',num2str(round(1000*rand(1))),'.wav']); wavwrite(D',SR,tmpfile); cmd = ['"',lame,'"', lameopts, '"',tmpfile, '" "', FILE, '"']; mysystem(cmd); % Delete tmp file mysystem([rmcmd, ' "', tmpfile,'"']); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function w = mysystem(cmd) % Run system command; report error; strip all but last line [s,w] = system(cmd); if s ~= 0 error(['unable to execute ',cmd,' (',w,')']); end % Keep just final line w = w((1+max([0,findstr(w,10)])):end); % Debug %disp([cmd,' -> ','*',w,'*']);
github
martinarielhartmann/mirtooloct-master
aiffread.m
.m
mirtooloct-master/MIRToolbox/aiffread.m
20,801
utf_8
9f46fe07573112dfe1958161a768a9c9
function [data,Fs,nBits,formChunk] = aiffread(filePath,indexRange) %AIFFREAD Read AIFF (Audio Interchange File Format) sound file. % Y = AIFFREAD(FILE) reads an AIFF file specified by the string FILE, % returning the sampled data in Y. The ".aif" extension is appended if no % extension is given. % % [Y,FS,NBITS,CHUNKDATA] = AIFFREAD(FILE) returns the sample rate (FS) in % Hertz, the number of bits per sample (NBITS) used to encode the data in % the file, and a complete structure of the chunk data (CHUNKDATA) % contained in the AIFF file (minus the actual audio data returned in Y). % See below for a description of CHUNKDATA. % % [...] = AIFFREAD(FILE,N) returns only the first N samples from each % channel in the file. % % [...] = AIFFREAD(FILE,[N1 N2]) returns only samples N1 through N2 from % each channel in the file. % % [SIZ,...] = AIFFREAD(FILE,'size') returns the size of the audio data % contained in the file in place of the actual audio data, where % SIZ = [nSampleFrames nChannels]. % %-NOTES-------------------------------------------------------------------- % % A note on compressed files: % % Both AIFF and AIFC/AIFF-C (compressed) file types can be read by % AIFFREAD, but the data returned for AIFC/AIFF-C files will be the % raw, compressed data (i.e. AIFFREAD loads the data from the file % without modification). Currently, since there are many compression % formats, it is the responsibility of the user to uncompress the % sound data using parameters defined in the COMM chunk (contained in % the returned CHUNKDATA structure). When loading AIFC/AIFF-C files, % any optional numerical subranges are ignored and the entire set of % compressed data is returned as a column vector of signed bytes % (INT8 type). % % A note on the CHUNKDATA structure: % % The CHUNKDATA structure has the following fields: % % -'chunkID': The 4-character ID for the chunk. This will always be % the string 'FORM'. % -'chunkSize': The size (in bytes) of the remaining data in the % file. % -'formType': A 4-character string for the file type that should % be either 'AIFF' or 'AIFC'. % -'chunkArray': An array of structures, one entry for every chunk % that is in the file (not counting this parent FORM % chunk). The fields of this structure are: % -'chunkID': The 4-character ID for the chunk. % -'chunkSize': The size (in bytes) of the % remaining data in the chunk. % -'chunkData': A structure of data for the % chunk. The form of this data for % a given chunkID can be found at % the links given below for the % file format standards. % % The data portion of certain chunks may not have a clearly defined % format, or that format may be dependent on the implementation or % application that will be using the data. In such cases, the data % returned for that chunk in the CHUNKDATA structure will be in a raw % format (vectors of signed or unsigned 8-bit integers) and it will be % up to the user/application to parse and format this data correctly. % The following is a list of such AIFF/AIFF-C chunks: % % -Audio Recording Chunk (chunkID = 'AESD'): The chunkData % structure has one field 'aesChannelStatusData' that stores a % column vector of 24 8-bit unsigned integers. % -Application Specific Chunk (chunkID = 'APPL'): The chunkData % structure has two fields. 'applicationSignature' stores a % 4-character string identifying the application. 'data' stores a % column vector of 8-bit signed integers. % -MIDI Data Chunk (chunkID = 'MIDI'): The chunkData structure has % one field 'midiData' that stores a column vector of 8-bit % unsigned integers. % -Sound Accelerator (SAXEL) Chunk (chunkID = 'SAXL'): There is no % finalized format for Saxel chunks, so the chunkData structure % follows the draft format given in Appendix D of the AIFF-C % standard. % % Description for the AIFF standard can be found here: % % http://muratnkonar.com/aiff/index.html % % Descriptions for the AIFC/AIFF-C standard can be found here: % % http://www.cnpbagwell.com/aiff-c.txt % http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/AIFF/Docs/... % AIFF-C.9.26.91.pdf % Author: Ken Eaton % Last modified: 3/17/09 %-------------------------------------------------------------------------- % Initializations: aiffChunkPrecedence = {'COMM' 'SSND' 'MARK' 'INST' 'COMT' 'NAME' ... 'AUTH' '[c] ' 'ANNO' 'AESD' 'MIDI' 'APPL'}; aiffChunkLimits = [1 1 1 1 1 1 1 1 inf 1 inf inf]; aifcChunkPrecedence = {'FVER' 'COMM' 'INST' 'SAXL' 'COMT' 'MARK' ... 'SSND' 'NAME' 'AUTH' '[c] ' 'ANNO' 'AESD' ... 'MIDI' 'APPL'}; aifcChunkLimits = [1 1 1 inf 1 1 1 1 1 1 inf 1 inf inf]; fid = -1; % Check the number of input arguments: switch nargin, case 0, error(error_message('notEnoughInputs')); case 1, indexRange = [1 inf]; end % Check the file name input argument: if ~ischar(filePath), error(error_message('badArgumentType','File name','char')); end [filePath,fileName,fileExtension] = fileparts(filePath); if isempty(fileExtension), fileExtension = '.aif'; end if ~any(strcmpi(fileExtension,{'.aif' '.afc' '.aiff' '.aifc'})), error(error_message('unknownExtension',fileExtension)); end % Check the optional input argument: if isnumeric(indexRange), % Numeric range specification indexRange = double(indexRange); nRange = numel(indexRange); if (nRange > 2) || any(indexRange < 1) || any(isnan(indexRange)), error(error_message('badIndexValue')); end indexRange = [ones(nRange ~= 2) round(indexRange) inf(nRange == 0)]; elseif ischar(indexRange), % Specification for returning just the size if ~strncmpi(indexRange,'size',numel(indexRange)), error(error_message('invalidString')); end indexRange = []; else % Invalid input error(error_message('badArgumentType','Optional argument',... 'numeric or char')); end % Check that the file exists and can be opened: fid = fopen(fullfile(filePath,[fileName fileExtension]),'r','b'); if fid == -1, error(error_message('invalidFile',[fileName fileExtension])); end % Initialize formChunk structure: formChunk = struct('chunkID',[],'chunkSize',[],'formType',[],... 'chunkArray',[]); % Read FORM chunk data: formChunk.chunkID = read_text(fid,4); if ~strcmp(formChunk.chunkID,'FORM'), error(error_message('invalidFileFormat',fileExtension)); end formChunk.chunkSize = fread(fid,1,'int32'); formType = read_text(fid,4); if ~any(strcmp(formType,{'AIFF' 'AIFC'})), error(error_message('invalidFileFormat',fileExtension)); end formChunk.formType = formType; % Since the order of chunks is not guaranteed, first skip through the % file and read just the chunkIDs and chunkSizes: iChunk = 0; chunkIDArray = {}; chunkSizeArray = {}; chunkDataIndex = []; nextChunkID = read_text(fid,4); while ~feof(fid), iChunk = iChunk+1; chunkIDArray{iChunk} = nextChunkID; chunkSize = fread(fid,1,'int32'); chunkSizeArray{iChunk} = chunkSize; chunkDataIndex(iChunk) = ftell(fid); fseek(fid,chunkSize+rem(chunkSize,2),'cof'); nextChunkID = read_text(fid,4); end % Check for the presence of required chunks: if ~ismember('COMM',chunkIDArray), error(error_message('missingChunk','COMM',formType)); end if strcmp(formType,'AIFC') && ~ismember('FVER',chunkIDArray), error(error_message('missingChunk','FVER',formType)); end % Check for unknown chunks and order chunks based on chunk precedence: if strcmp(formType,'AIFF'), [isChunk,orderIndex] = ismember(chunkIDArray,aiffChunkPrecedence); else [isChunk,orderIndex] = ismember(chunkIDArray,aifcChunkPrecedence); end if ~all(isChunk), unknownChunks = [chunkIDArray(~isChunk); ... repmat({', '},1,sum(~isChunk)-1) {'.'}]; orderIndex = orderIndex(isChunk); chunkIDArray = chunkIDArray(isChunk); chunkSizeArray = chunkSizeArray(isChunk); chunkDataIndex = chunkDataIndex(isChunk); warning('aiffread:unknownChunk',... ['The following chunk IDs are unknown for an ' formType ... ' file and will be ignored: ' unknownChunks{:}]); end [index,orderIndex] = sort(orderIndex); chunkIDArray = chunkIDArray(orderIndex); chunkSizeArray = chunkSizeArray(orderIndex); chunkDataIndex = chunkDataIndex(orderIndex); % Check for chunks that should not appear more than once: index = unique(index(diff(index) < 1)); if strcmp(formType,'AIFF'), repeatChunks = aiffChunkPrecedence(aiffChunkLimits(index) == 1); else repeatChunks = aifcChunkPrecedence(aifcChunkLimits(index) == 1); end if ~isempty(repeatChunks), repeatChunks = [repeatChunks; ... repmat({', '},1,numel(repeatChunks)-1) {'.'}]; error(error_message('repeatChunk',formType,[repeatChunks{:}])); end % Initialize chunkArray data: formChunk.chunkArray = struct('chunkID',chunkIDArray,... 'chunkSize',chunkSizeArray,... 'chunkData',[]); % Read the data for each chunk: for iChunk = 1:numel(chunkIDArray), chunkData = []; fseek(fid,chunkDataIndex(iChunk),'bof'); switch chunkIDArray{iChunk}, case '[c] ', % Copyright Chunk chunkData.text = read_text(fid,chunkSizeArray{iChunk}); case 'AESD', % Audio Recording Chunk chunkData.aesChannelStatusData = ... fread(fid,[chunkSizeArray{iChunk} 1],'*uint8'); case 'ANNO', % Annotation Chunk chunkData.text = read_text(fid,chunkSizeArray{iChunk}); case 'APPL', % Application Specific Chunk chunkData.applicationSignature = read_text(fid,4); chunkData.data = fread(fid,[chunkSizeArray{iChunk}-4 1],'*int8'); case 'AUTH', % Author Chunk chunkData.text = read_text(fid,chunkSizeArray{iChunk}); case 'COMM', % Common Chunk nChannels = fread(fid,1,'int16'); chunkData.nChannels = nChannels; nSampleFrames = fread(fid,1,'uint32'); if (nSampleFrames > 0) && ~ismember('SSND',chunkIDArray), error(error_message('missingChunk','SSND',formType)); end chunkData.nSampleFrames = nSampleFrames; nBits = fread(fid,1,'int16'); chunkData.sampleSize = nBits; exponent = fread(fid,1,'uint16'); highMantissa = fread(fid,1,'uint32'); lowMantissa = fread(fid,1,'uint32'); Fs = extended2double(exponent,highMantissa,lowMantissa); chunkData.sampleRate = Fs; if strcmp(formType,'AIFF'), compressionType = 'NONE'; else compressionType = read_text(fid,4); chunkData.compressionType = compressionType; chunkData.compressionName = read_pstring(fid); end case 'COMT', % Comments Chunk nComments = fread(fid,1,'uint16'); chunkData.nComments = nComments; chunkData.commentArray = struct('timeStamp',cell(nComments,1),... 'marker',[],'count',[],'text',[]); for iComment = 1:nComments, chunkData.commentArray(iComment) = read_comment(fid); end case 'FVER', % Format Version Chunk (AIFC/AIFF-C only) timeStamp = fread(fid,1,'uint32'); if timeStamp ~= 2726318400, warning('aiffread:unknownVersion',... ['File contains an unrecognized version of the ' ... 'AIFC/AIFF-C standard.']); end chunkData.timeStamp = timeStamp; case 'INST', % Instrument Chunk chunkData.baseNote = fread(fid,1,'int8'); chunkData.detune = fread(fid,1,'int8'); chunkData.lowNote = fread(fid,1,'int8'); chunkData.highNote = fread(fid,1,'int8'); chunkData.lowVelocity = fread(fid,1,'int8'); chunkData.highVelocity = fread(fid,1,'int8'); chunkData.gain = fread(fid,1,'int16'); chunkData.sustainLoop = read_loop(fid); chunkData.releaseLoop = read_loop(fid); case 'MARK', % Marker Chunk nMarkers = fread(fid,1,'uint16'); chunkData.nMarkers = nMarkers; chunkData.markerArray = struct('id',cell(nMarkers,1),... 'position',[],'markerName',[]); for iMarker = 1:nMarkers, chunkData.markerArray(iMarker) = read_marker(fid); end markerIDs = [chunkData.markerArray.id]; if any(markerIDs < 1) || (numel(unique(markerIDs)) < nMarkers), warning('aiffread:invalidMarkers',... 'Invalid or repeated marker IDs were detected.'); end case 'MIDI', % MIDI Data Chunk chunkData.midiData = fread(fid,[chunkSizeArray{iChunk} 1],... '*uint8'); case 'NAME', % Name Chunk chunkData.text = read_text(fid,chunkSizeArray{iChunk}); case 'SAXL', % Sound Accelerator (SAXEL) Chunk (AIFC/AIFF-C only) nSaxels = fread(fid,1,'uint16'); chunkData.nSaxels = nSaxels; chunkData.saxelArray = struct('id',cell(nSaxels,1),'size',[],... 'saxelData',[]); for iSaxel = 1:nSaxels, chunkData.saxelArray(iSaxel) = read_saxel(fid); end case 'SSND', % Sound Data Chunk nBytes = ceil(nBits/8); chunkData.offset = fread(fid,1,'uint32'); chunkData.blockSize = fread(fid,1,'uint32'); if isempty(indexRange), data = [nSampleFrames nChannels]; elseif strcmp(compressionType,'NONE'), if (chunkSizeArray{iChunk}-8 ~= nChannels*nSampleFrames*nBytes), error(error_message('sizeMismatch')); end fseek(fid,nBytes*nChannels*(indexRange(1)-1),'cof'); nRead = min(indexRange(2),nSampleFrames)-indexRange(1)+1; data = fread(fid,[nChannels nRead],['*bit' int2str(nBytes*8)]).'; if nBits < nBytes*8, data = data./(2^(nBytes*8-nBits)); end else data = fread(fid,[chunkSizeArray{iChunk}-8 1],'*int8'); end end formChunk.chunkArray(iChunk).chunkData = chunkData; end % Close the file: fclose(fid); %~~~Begin nested functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %------------------------------------------------------------------------ function errorStruct = error_message(errorCode,varargin) % % Initialize an error message (and close open files, if necessary). % %------------------------------------------------------------------------ % Close open files, if necessary: if ~isempty(fopen(fid)), fclose(fid); end % Initialize error message text: switch errorCode, case 'badArgumentType', errorText = [varargin{1} ' should be of type ' varargin{2} '.']; case 'badIndexValue', errorText = ['Index range must be specified as a scalar or ' ... '2-element vector of positive, non-zero, non-NaN ' ... 'values.']; case 'invalidFile', errorText = ['Could not open file ''' varargin{1} '''.']; case 'invalidFileFormat', errorText = ['Not a valid ' varargin{1} ' file.']; case 'invalidString', errorText = '''size'' is the only valid string argument.'; case 'missingChunk', errorText = ['''' varargin{1} ''' chunk is required for a ' ... varargin{2} ' file.']; case 'notEnoughInputs', errorText = 'Not enough input arguments.'; case 'repeatChunk', errorText = ['The following chunk IDs should not appear more ' ... 'than once in an ' varargin{1} ' file: ' varargin{2}]; case 'sizeMismatch', errorText = 'Data size mismatch between COMM and SSND chunks.'; case 'unknownExtension', errorText = ['Unknown file extension ''' varargin{1} '''.']; end % Create error structure: errorStruct = struct('message',errorText,... 'identifier',['aiffread:' errorCode]); end %~~~End nested functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ end %~~~Begin subfunctions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %-------------------------------------------------------------------------- function value = extended2double(exponent,highMantissa,lowMantissa) % % Converts an 80-bit extended floating-point type to a double. % %-------------------------------------------------------------------------- signBit = bitand(exponent,32768); exponent = bitand(exponent,32767); highMantissa = bitand(highMantissa,4294967295); lowMantissa = bitand(lowMantissa,4294967295); if (exponent == 0) && (highMantissa == 0) && (lowMantissa == 0), value = 0; elseif exponent == 32767, if (highMantissa > 0) || (lowMantissa > 0), value = nan; else value = inf; end else value = highMantissa*2^(exponent-16414)+lowMantissa*2^(exponent-16446); end if signBit, value = -value; end end %-------------------------------------------------------------------------- function commentStruct = read_comment(fid) % % Reads a structure of comment data from a file. % %-------------------------------------------------------------------------- commentStruct = struct('timeStamp',fread(fid,1,'uint32'),... 'marker',fread(fid,1,'int16'),... 'count',[],'text',[]); charCount = fread(fid,1,'uint16'); commentStruct.count = charCount; commentStruct.text = read_text(fid,charCount); end %-------------------------------------------------------------------------- function loopStruct = read_loop(fid) % % Reads a structure of loop data from a file. % %-------------------------------------------------------------------------- loopStruct = struct('playMode',fread(fid,1,'int16'),... 'beginLoop',fread(fid,1,'int16'),... 'endLoop',fread(fid,1,'int16')); end %-------------------------------------------------------------------------- function markerStruct = read_marker(fid) % % Reads a structure of marker data from a file. % %-------------------------------------------------------------------------- markerStruct = struct('id',fread(fid,1,'int16'),... 'position',fread(fid,1,'uint32'),... 'markerName',read_pstring(fid)); end %-------------------------------------------------------------------------- function pascalString = read_pstring(fid) % % Reads a Pascal-style string from a file, and afterwards shifts the file % pointer ahead by one byte if necessary to make the total number of bytes % read an even number. % %-------------------------------------------------------------------------- charCount = fread(fid,1,'uint8'); pascalString = fread(fid,[1 charCount],'int8=>char'); if rem(charCount+1,2), fseek(fid,1,'cof'); end end %-------------------------------------------------------------------------- function saxelStruct = read_saxel(fid) % % Reads a structure of saxel data from a file. % %-------------------------------------------------------------------------- saxelStruct = struct('id',fread(fid,1,'int16'),'size',[],'saxelData',[]); saxelBytes = fread(fid,1,'uint16'); saxelStruct.size = saxelBytes; saxelStruct.saxelData = fread(fid,[saxelBytes 1],'*int8'); if rem(saxelBytes,2), fseek(fid,1,'cof'); end end %-------------------------------------------------------------------------- function textString = read_text(fid,charCount) % % Reads ASCII text from a file, and afterwards shifts the file pointer % ahead by one byte if necessary to make the total number of bytes read an % even number. % %-------------------------------------------------------------------------- textString = fread(fid,[1 charCount],'int8=>char'); if rem(charCount,2), fseek(fid,1,'cof'); end end %~~~End subfunctions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
github
martinarielhartmann/mirtooloct-master
mireval.m
.m
mirtooloct-master/MIRToolbox/mireval.m
11,804
utf_8
4eacc02021f6cd564db73d97187f9875
function v = mireval(d,file,single,export) % mireval(d,filename) applies the mirdesign object d to the audio file % named filename. % mireval(d,'Folder') applied the mirdesign object to each audio files in % the current directory. % mireval(d,'Folders') applied the mirdesign object recursively to the % subfolders. % Optional argument: mireval(...,'Single') only keeps the first % output when several output are returned for a given mirdesign % object. % mireval performs the actual evaluation of the design flowchart. % If 'Folder' is used, the evaluation is carried out for each audio file % successively. % If d is a structure or a cell array, evaluate each component % separately. % The evaluation starts with a top-down traversal of the design flowchart % (evaleach). if not(ischar(file) || (iscell(file) && ischar(file{1}))) error('ERROR IN MIREVAL: the second input should be a file name or ''Folder''') end if nargin<3 single = []; end if nargin<4 export = []; end % First, let's look at the content of the file(s): size, sampling rate, % etc. w = []; % Array containing the index positions of the starting and ending dates. s = getsize(d); ch = 1; if ~iscell(file) && (strcmpi(file,'Folder') || strcmpi(file,'Folders')) [l w sr lg a] = evalfolder('',s,0,[],[],[],{},strcmpi(file,'Folders')); if l == 0 disp('No sound file detected in this folder.') end elseif iscell(file) || (length(file)>3 && strcmpi(file(end-3:end),'.txt')) if iscell(file) a = file; else a = importdata(file); end l = length(a); w = zeros(2,l); sr = zeros(1,l); lg = zeros(1,l); for i = 1:l [di,tpi,fpi,fi,lg(i)] = mirread([],a{i},0,0,0); if not(isempty(s)) interval = s(1:2); if s(3) interval = round(interval*fi)+1; end if s(4) == 1 interval = interval+round(di/2); elseif s(4) == 2 interval = interval+di; end w(:,i) = min(max(interval,1),di); else w(:,i) = [1;di]; end if getsampling(d) sr(i) = getsampling(d); else sr(i) = fi; end end else l = 1; [d1,tp1,fp1,f1,lg,b,n,ch] = mirread([],file,0,0,0); if length(s)>1 interval = s(1:2)'; if s(3) interval = round(interval*f1)+1; end if s(4) == 1 interval = interval+round(d1/2); elseif s(4) == 2 interval = interval+d1; end if d1 < interval(2) warning('WARNING IN MIRAUDIO: The temporal region to be extracted exceeds the temporal extent of the whole audio file.'); end w = min(max(interval,1),d1); else w = [1;d1]; end if isa(d,'mirdesign') && getsampling(d) sr = getsampling(d); else sr = f1; end a = {file}; end if not(l) v = []; return end order = 1:l; if isa(d,'mirdesign') && isequal(get(d,'Method'),@mirplay) op = get(d,'Option'); if isfield(op,'inc') if not(isnumeric(op.inc)) op.inc = mirgetdata(op.inc); end [unused order] = sort(op.inc); elseif isfield(op,'dec') if not(isnumeric(op.inc)) op.inc = mirgetdata(op.inc); end [unused order] = sort(op.dec,'descend'); end if isfield(op,'every') order = order(1:op.every:end); end order = order(:)'; end parallel = 0; if mirparallel try if mirparallel == 1 || mirparallel == Inf matlabpool; else matlabpool(mirparallel); end parallel = 1; catch warning('mirparallel cannot open matlabpool because it is already used.'); end end if parallel % The evaluation is carried out for each audio file successively % (or in parallel). y = mirevalparallel(d,a,sr,lg,w,single,ch,export); isstat = 0; else % The evaluation is carried out for each audio file successively. y = cell(1,l); isstat = isfield(d,'Stat'); for i = 1:length(order) f = order(i); if l > 1 fprintf('\n') display(['*** File # ',num2str(i),'/',num2str(l),': ',a{f}]); end if mirverbose tic end yf = mirevalaudiofile(d,a{f},sr(f),lg(f),w(:,f),{},0,f,single,'',ch); if mirverbose toc end y{f} = yf; if (mirtemporary && length(order)>1) || not(isempty(export)) if 0 % Private use. ff = find(a{f} == '/'); if isempty(ff) ff = 0; else ff = ff(end); end listing = dir([a{f}(1:ff),'Fabien''s annotations/',... a{f}(ff+1:end-4),'*']); an = importdata([a{f}(1:ff),'Fabien''s annotations/',... listing.name]); dt1 = mirgetdata(yf.t1); ok1 = find(dt1 > an*.96 & dt1 < an*1.04); if isempty(ok1) ok1 = 0; end dt2 = mirgetdata(yf.t2); ok2 = find(dt2 > an*.96 & dt2 < an*1.04); if isempty(ok2) ok2 = 0; end if isempty(export) export = 'mirtemporary.txt'; end if strncmpi(export,'Separately',10) filename = a{f}; %filename(filename == '/') = '.'; %filename = ['Backup/' filename]; filename = [filename export(11:end)]; %if i == 1 % mkdir('Backup'); %end mirexport(filename,yf); elseif i==1 mirexport([export,'1'],ok1,an,yf.t1); mirexport([export,'2'],ok2,an,yf.t2); else mirexport([export,'1'],ok1,an,yf.t1,'#add'); mirexport([export,'2'],ok2,an,yf.t2,'#add'); end else if isempty(export) export = 'mirtemporary.txt'; end if strncmpi(export,'Separately',10) filename = a{f}; filename(filename == '/') = '.'; filename = ['Backup/' filename export(11:end)]; if i == 1 mkdir('Backup'); end mirexport(filename,yf); elseif i==1 mirexport(export,yf); else mirexport(export,yf,'#add'); end end end clear yf end end v = combineaudiofile(a,isstat,y{:}); function c = combineaudiofile(filename,isstat,varargin) % Combine output from several audio files into one single c = varargin{1}; % The (series of) input(s) related to the first audio file if isempty(c) return end if isstruct(c) for j = 1:length(varargin) if j == 1 fields = fieldnames(varargin{1}); else fields = union(fields,fieldnames(varargin{j})); end end for i = 1:length(fields) field = fields{i}; v = {}; for j = 1:length(varargin) if isfield(varargin{j},field) v{j} = varargin{j}.(field); else v{j} = NaN; end end c.(field) = combineaudiofile('',isstat,v{:}); if strcmp(field,'Class') c.Class = c.Class{1}; end end if not(isempty(filename)) && isstat c.FileNames = filename; end return end if ischar(c) c = varargin; return end if (not(iscell(c)) && not(isa(c,'mirdata'))) for j = 1:length(varargin) if j == 1 lv = size(varargin{j},1); else lv = max(lv,size(varargin{j},1)); end end c = NaN(lv,length(varargin)); for i = 1:length(varargin) if not(isempty(varargin{i})) c(1:length(varargin{i}),i) = varargin{i}; end end return end if (iscell(c) && not(isa(c{1},'mirdata'))) for i = 1:length(c) v = cell(1,nargin-2); for j = 1:nargin-2 v{j} = varargin{j}{i}; end c{i} = combineaudiofile(filename,isstat,v{:}); end return end if not(iscell(c)) c = {c}; end nv = length(c); % The number of input variables for each different audio file for j = 1:nv % Combine files for each different input variable v = varargin; for i = 1:length(varargin) if iscell(v{i}) v{i} = v{i}{j}; end end if not(isempty(v)) && not(isempty(v{1})) c{j} = combine(v{:}); end end function s = getsize(d) if isa(d,'mirstruct') d = get(d,'Data'); if isempty(d) error('ERROR in MIREVAL: Your mirstruct object does not have any field (besides tmp).'); s = 0; else s = getsize(d{1}); end elseif isstruct(d) fields = fieldnames(d); s = getsize(d.(fields{1})); elseif iscell(d) s = getsize(d{1}); else s = get(d,'Size'); % Starting and ending dates in seconds. end function d2 = sortnames(d,d2,n) if length(n) == 1 d2(end+1) = d(1); return end first = zeros(1,length(n)); for i = 1:length(n) if isempty(n{i}) first(i) = -Inf; else ni = n{i}{1}; if ischar(ni) first(i) = ni-10058; else first(i) = ni; end end end [o i] = sort(first); n = {n{i}}; d = d(i); i = 0; while i<length(n) i = i+1; if isempty(n{i}) d2(end+1) = d(i); else dmp = (d(i)); tmp = {n{i}(2:end)}; while i+1<=length(n) && n{i+1}{1} == n{i}{1}; i = i+1; dmp(end+1) = d(i); tmp{end+1} = n{i}(2:end); end d2 = sortnames(dmp,d2,tmp); end end function [l w sr lg a] = evalfolder(path,s,l,w,sr,lg,a,folders) if not(isempty(path)) path = [path '/']; end dd = dir; dn = {dd.name}; nn = cell(1,length(dn)); % Modified file names for i = 1:length(dn) % Each file name is considered j = 0; while j<length(dn{i}) % Each successive character is modified if necessary j = j+1; tmp = dn{i}(j) - '0'; if tmp>=0 && tmp<=9 while j+1<length(dn{i}) && dn{i}(j+1)>='0' && dn{i}(j+1)<='9' j = j+1; tmp = tmp*10 + (dn{i}(j)-'0'); end else tmp = dn{i}(j); end nn{i}{end+1} = tmp; end end dd = sortnames(dd,[],nn); for i = 1:length(dd); nf = dd(i).name; if folders && dd(i).isdir if not(strcmp(nf(1),'.')) cd(dd(i).name) [l w sr lg a] = evalfolder([path nf],s,l,w,sr,lg,a,1); cd .. end else [di,tpi,fpi,fi,li,bi,ni] = mirread([],nf,0,1,0); if not(isempty(ni)) l = l+1; if not(isempty(s)) interval = s(1:2); if s(3) interval = round(interval*fi)+1; end if s(4) == 1 interval = interval+round(di/2); elseif s(4) == 2 interval = interval+di; end w(:,l) = min(max(interval,1),di); else w(:,l) = [1;di]; end sr(l) = fi; lg(l) = li; a{l} = [path ni]; end end end
github
martinarielhartmann/mirtooloct-master
mirmode.m
.m
mirtooloct-master/MIRToolbox/mirmode.m
1,291
utf_8
0b956b8a46df510afed36b5b138ecdb2
function varargout = mirmode(x,varargin) % m = mirmode(a) estimates the mode. A value of 0 indicates a complete % incertainty, whereas a positive value indicates a dominance of % major mode and a negative value indicates a dominance of minor mode. % Optional arguments: % mirmode(a,s) specifies a strategy. % Possible values for s: 'Sum', 'Best'(default) stra.type = 'String'; stra.default = 'Best'; stra.choice = {'Best','Sum','Major','SumBest'}; option.stra = stra; specif.option = option; specif.defaultframelength = 1; specif.defaultframehop = .5; varargout = mirfunction(@mirmode,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirkeystrength')) x = mirkeystrength(x); end type = 'mirscalar'; function o = main(s,option,postoption) if iscell(s) s = s{1}; end m = get(s,'Data'); v = mircompute(str2func(['algo' lower(option.stra)]),m); b = mirscalar(s,'Data',v,'Title','Mode'); o = {b,s}; function v = algosum(m) v = sum(abs(m(:,:,:,1) - m(:,:,:,2))); function v = algobest(m) v = max(m(:,:,:,1)) - max(m(:,:,:,2)); function v = algosumbest(m) m = max(.5,m)-.5; v = sum(m(:,:,:,1)) - sum(m(:,:,:,2)); function v = algomajor(m) m = max(.5,m)-.5; v = sum(m(:,:,1));
github
martinarielhartmann/mirtooloct-master
mirstat.m
.m
mirtooloct-master/MIRToolbox/mirstat.m
8,336
utf_8
b095df8141f86e3ba1f19c9a49f92ef4
function varargout = mirstat(f,varargin) % stat = mirstat(f) returns basic statistics of the feature f as a % structure array stat such that: % stat.Mean is the mean of the feature; % stat.Std is the standard deviation; % stat.Slope is the linear slope of the curve; % stat.PeriodFreq is the frequency (in Hz) of the main periodicity; % stat.PeriodAmp is the normalized amplitude of the main periodicity; % stat.PeriodEntropy is the entropy of the periodicity curve. % The main periodicity and periodicity curve are evaluated through the % computation of the autocorrelation sequence related to f. % % f can be itself a structure array composed of features. In this case, % stat will be structured the same way. % % mirstat does not work for multi-channels objects. if isa(f,'mirstruct') varargout = {set(f,'Stat',1)}; elseif isstruct(f) if isdesign(f) f.Stat = 1; varargout = {f}; else fields = fieldnames(f); for i = 1:length(fields) field = fields{i}; ff = f.(field); if iscell(ff) && isa(ff{1},'mirdata') ff = ff{1}; end if isa(ff,'mirdata') if i == 1 la = get(ff,'Label'); if not(isempty(la) || isempty(la{1})) stat.Class = la; end end ff = set(ff,'Label',''); end stat.(field) = mirstat(ff,'FileNames',0); end if isempty(varargin) f0 = f; while isstruct(f0) fields = fieldnames(f0); f0 = f0.(fields{1}); end if iscell(f0) f0 = f0{1}; end stat.FileNames = get(f0,'Name'); end varargout = {stat}; end elseif iscell(f) if 0 %ischar(f{1}) varargout = {f}; else res = zeros(length(f),1); for i = 1:length(f) res(i) = mirstat(f{i}); end varargout = {res}; end elseif isnumeric(f) f(isnan(f)) = []; varargout = {mean(f)}; else alongfiles.key = 'AlongFiles'; alongfiles.type = 'Boolean'; alongfiles.default = 0; option.alongfiles = alongfiles; filenames.key = 'FileNames'; filenames.type = 'Boolean'; filenames.default = 1; option.filenames = filenames; specif.option = option; specif.nochunk = 1; varargout = mirfunction(@mirstat,f,varargin,nargout,specif,@init,@main); end function [x type] = init(x,option) type = ''; function stat = main(f,option,postoption) if iscell(f) f = f{1}; end if isa(f,'mirhisto') warning('WARNING IN MIRSTAT: histograms are not taken into consideration yet.') stat = struct; return end fp = get(f,'FramePos'); if haspeaks(f) ppp = get(f,'PeakPrecisePos'); if not(isempty(ppp)) && not(isempty(ppp{1})) stat = addstat(struct,ppp,fp,'PeakPos'); stat = addstat(stat,get(f,'PeakPreciseVal'),fp,'PeakMag'); else if isa(f,'mirkeystrength') || (isa(f,'mirchromagram') && get(f,'Wrap')) stat = struct; % This needs to be defined using some kind of circular statistics.. else stat = addstat(struct,get(f,'PeakPosUnit'),fp,'PeakPos'); end stat = addstat(stat,get(f,'PeakVal'),fp,'PeakMag'); end else stat = addstat(struct,get(f,'Data'),fp,'',option.alongfiles,... get(f,'Name'),get(f,'Label')); end if option.filenames stat.FileNames = get(f,'Name'); end function stat = addstat(stat,d,fp,field,alongfiles,filename,labels) l = length(d); if nargin<5 alongfiles = 0; end if nargin<7 labels = {}; end if not(alongfiles) || l == 1 anyframe = 0; for i = 1:l if not(iscell(d{i})) d{i} = {d{i}}; end for k = 1:length(d{i}) dd = d{i}{k}; if iscell(dd) if length(dd)>1 anyframe = 1; end dn = cell2array(dd); [m{i}{k},s{i}{k},sl{i}{k},pa{i}{k},pf{i}{k},pe{i}{k}] ... = computestat(dn,fp{i}{k}); elseif size(dd,2) < 2 nonan = find(not(isnan(dd))); dn = dd(nonan); if isempty(dn) m{i}{k} = NaN; else m{i}{k} = mean(dn,2); end s{i}{k} = NaN; sl{i}{k} = NaN; pa{i}{k} = NaN; pf{i}{k} = NaN; pe{i}{k} = NaN; else anyframe = 1; s1 = size(dd,1); s3 = size(dd,3); dd = mean(dd,4); %mean(dd,3),4); m{i}{k} = NaN(s1,1,s3); s{i}{k} = NaN(s1,1,s3); sl{i}{k} = NaN(s1,1,s3); pa{i}{k} = NaN(s1,1,s3); pf{i}{k} = NaN(s1,1,s3); pe{i}{k} = NaN(s1,1,s3); for h = 1:s3 for j = 1:s1 [m{i}{k}(j,1,h),s{i}{k}(j,1,h),sl{i}{k}(j,1,h),... pa{i}{k}(j,1,h),pf{i}{k}(j,1,h),pe{i}{k}(j,1,h)] = ... computestat(dd(j,:,h),fp{i}{k}); end end end end end if anyframe fields = {'Mean','Std','Slope','PeriodFreq','PeriodAmp','PeriodEntropy'}; stats = {m,s,sl,pf,pa,pe}; else fields = {'Mean'}; stats = {m}; end for i = 1:length(stats) data = stats{i}; data = uncell(data,NaN); stat.(strcat(field,fields{i})) = data; end else if iscell(d{1}{1}) slash = strfind(filename{1},'/'); nbfolders = 1; infolder = 0; foldername{1} = filename{1}(1:slash(end)-1); for i = 1:length(d) slash = strfind(filename{i},'/'); if not(strcmpi(filename{i}(1:slash(end)-1),foldername)) nbfolders = nbfolders + 1; infolder = 0; foldername{nbfolders} = filename{i}(1:slash(end)-1); end infolder = infolder+1; dd{nbfolders}(infolder,:) = cell2array(d{i}{1}); end for i = 1:length(dd) figure plot(dd{i}') stat.Mean{i} = mean(dd{i}); stat.Std{i} = std(dd{i}); end end end if not(isempty(labels) || isempty(labels{1})) stat.Class = labels; end function dn = cell2array(dd) dn = zeros(1,length(dd)); for j = 1:length(dd) if isempty(dd{j}) dn(j) = NaN; else dn(j) = dd{j}(1); end end function [m,s,sl,pa,pf,pe] = computestat(d,fp) m = NaN; s = NaN; sl = NaN; pa = NaN; pf = NaN; pe = NaN; diffp = fp(1,2:end) - fp(1,1:end-1); if isempty(diffp) || sum(round((diffp(2:end)-diffp(1:end-1))*1000)) % Not regular sampling (in mirattacktime for instance) framesampling = NaN; else framesampling = fp(1,2)-fp(1,1); end nonan = find(not(isnan(d))); if not(isempty(nonan)) dn = d(nonan); m = mean(dn,2); s = std(dn,0,2); if not(isnan(s)) if s dk = (dn-m)/s; tk = linspace(0,1,size(d,2)); sl = dk(:)'/tk(nonan); elseif size(s,2) == 1 s = NaN; end end if length(dn)>1 cor = xcorr(dn',dn','coeff'); cor = cor(ceil(length(cor)/2):end); % let's zero the first descending slope of the % autocorrelation function firstmin = find(cor(2:end)>cor(1:end-1)); if not(isempty(firstmin) || isnan(framesampling)) cor2 = cor; cor2(1:firstmin(1)) = 0; [pa,pfk] = max(cor2); if pfk > 1 pf = 1/(pfk-1)/framesampling; end end cor = abs(cor); cor = cor/sum(cor); pe = -sum(cor.*log(cor+1e-12))./log(length(cor)); end end function b = isdesign(f) if iscell(f) f = f{1}; end if isa(f,'mirdesign') || isa(f,'mirstruct') b = 1; elseif isa(f,'mirdata') || not(isstruct(f)) b = 0; else fields = fieldnames(f); b = isdesign(f.(fields{1})); end
github
martinarielhartmann/mirtooloct-master
mirlength.m
.m
mirtooloct-master/MIRToolbox/mirlength.m
1,393
utf_8
21e35d00ed2dbfaa0e4a83a2165a1f2f
function varargout = mirlength(orig,varargin) % mirlength(x) indicates the temporal length of x. % If x is decomposed into frames, % mirlength(x) indicates the frame length, whereas % mirlength(x,'Global') indicates the total temporal spanning of the % frame decomposition. % Optional argument: % mirlength(...,'Unit',u) indicates the length unit. % Possible values: % u = 'Second': duration in seconds (Default). % u = 'Sample': length in number of samples. unit.key = 'Unit'; unit.type = 'String'; unit.choice = {'Second','Sample'}; unit.default = 'Second'; option.unit = unit; specif.option = option; varargout = mirfunction(@mirlength,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'mirscalar'; function z = main(a,option,postoption) if iscell(a) a = a{1}; end d = get(a,'Data'); f = get(a,'Sampling'); v = cell(1,length(d)); for h = 1:length(d) v{h} = cell(1,length(d{h})); for i = 1:length(d{h}) di = d{h}{i}; v{h}{i} = size(d{h}{i},1); if strcmp(option.unit,'Second') v{h}{i} = v{h}{i}/f{h}; end end end z = mirscalar(a,'Data',v,'Title','Temporal length'); if strcmp(option.unit,'Second') z = set(z,'Unit','s.'); else z = set(z,'Unit','samples.'); end
github
martinarielhartmann/mirtooloct-master
mirzerocross.m
.m
mirtooloct-master/MIRToolbox/mirzerocross.m
2,298
utf_8
26d2924ca563e0f4eac9d3f2b5793858
function varargout = mirzerocross(orig,varargin) % mirzeroscross(x) computes the sign-changes rate along the signal x, % i.e., how many time the waveform crosses the X-axis. When applied on % an audio waveform, gives a notion of noise. % Optional argument: % mirzerocross(...,'Per',p) precises the temporal reference for the % rate computation. % Possible values: % p = 'Second': number of sign-changes per second (Default). % p = 'Sample': number of sign-changes divided by the total % number of samples. % The 'Second' option returns a result equal to the one returned % by the 'Sample' option multiplied by the sampling rate. % mirzerocross(...,'Dir',d) precises the definition of sign change. % Possible values: % d = 'One': number of sign-changes from negative to positive % only (or, equivalently, from positive to negative only). % (Default) % d = 'Both': number of sign-changes in both ways. % The 'Both' option returns a result equal to twice the one % returned by the 'One' option. per.key = 'Per'; per.type = 'String'; per.choice = {'Second','Sample'}; per.default = 'Second'; option.per = per; dir.key = 'Dir'; dir.type = 'String'; dir.choice = {'One','Both'}; dir.default = 'One'; option.dir = dir; specif.option = option; varargout = mirfunction(@mirzerocross,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirdata')) x = miraudio(x); end type = 'mirscalar'; function z = main(a,option,postoption) if iscell(a) a = a{1}; end d = get(a,'Data'); f = get(a,'Sampling'); v = cell(1,length(d)); for h = 1:length(d) v{h} = cell(1,length(d{h})); for i = 1:length(d{h}) di = d{h}{i}; nl = size(di,1); zc = sum( di(2:end,:,:).*di(1:(end-1),:,:) < 0 ) /nl; if strcmp(option.per,'Second') zc = zc*f{h}; end if strcmp(option.dir,'One') zc = zc/2; end v{h}{i} = zc; end end z = mirscalar(a,'Data',v,'Title','Zero-crossing rate');
github
martinarielhartmann/mirtooloct-master
mp3read.m
.m
mirtooloct-master/MIRToolbox/mp3read.m
12,209
utf_8
b0b052ee491ef354631f3eaad6bbc0f7
function [Y,FS,NBITS,OPTS] = mp3read(FILE,N,MONO,DOWNSAMP,DELAY) % MP3READ Read MP3 audio file via use of external binaries. % Y = MP3READ(FILE) reads an mp3-encoded audio file into the % vector Y just like wavread reads a wav-encoded file (one channel % per column). Extension ".mp3" is added if FILE has none. % Also accepts other formats of wavread, such as % Y = MP3READ(FILE,N) to read just the first N sample frames (N % scalar), or the frames from N(1) to N(2) if N is a two-element vector. % Y = MP3READ(FILE,FMT) or Y = mp3read(FILE,N,FMT) % with FMT as 'native' returns int16 samples instead of doubles; % FMT can be 'double' for default behavior (to exactly mirror the % syntax of wavread). % % [Y,FS,NBITS,OPTS] = MP3READ(FILE...) returns extra information: % FS is the sampling rate, NBITS is the bit depth (always 16), % OPTS.fmt is a format info string; OPTS has multiple other % fields, see WAVREAD. % % SIZ = MP3READ(FILE,'size') returns the size of the audio data contained % in the file in place of the actual audio data, returning the % 2-element vector SIZ=[samples channels]. % % [Y...] = MP3READ(FILE,N,MONO,DOWNSAMP,DELAY) extends the % WAVREAD syntax to allow access to special features of the % mpg123 engine: MONO = 1 forces output to be mono (by % averaging stereo channels); DOWNSAMP = 2 or 4 downsamples by % a factor of 2 or 4 (thus FS returns as 22050 or 11025 % respectively for a 44 kHz mp3 file); % To accommodate a bug in mpg123-0.59, DELAY controls how many % "warm up" samples to drop at the start of the file; the % default value of 2257 makes an mp3write/mp3read loop for a 44 % kHz mp3 file be as close as possible to being temporally % aligned; specify as 0 to prevent discard of initial samples. % For later versions of mpg123 (e.g. 1.9.0) this is not needed; % a flag in mp3read.m makes the default DELAY zero in this case. % % [Y...] = MP3READ(URL...) uses the built-in network % functionality of mpg123 to read an MP3 file across the % network. URL must be of the form 'http://...' or % 'ftp://...'. 'size' and OPTS are not available in this mode. % % Example: % To read an mp3 file as doubles at its original width and sampling rate: % [Y,FS] = mp3read('piano.mp3'); % To read the first 1 second of the same file, downsampled by a % factor of 4, cast to mono, using the default filename % extension: % [Y,FS4] = mp3read('piano', FS/4, 1, 4); % % Note: Because the mp3 format encodes samples in blocks of 26 ms (at % 44 kHz), and because of the "warm up" period of the encoder, % the file length may not be exactly what you expect, depending % on your version of mpg123 (recent versions fix warmup). % % Note: requires external binaries mpg123 and mp3info; you % can find binaries for several platforms at: % http://labrosa.ee.columbia.edu/matlab/mp3read.html % % See also mp3write, wavread. % $Header: /Users/dpwe/matlab/columbiafns/RCS/mp3read.m,v 1.6 2009/12/08 16:35:23 dpwe Exp dpwe $ % 2003-07-20 [email protected] This version calls mpg123. % 2004-08-31 Fixed to read whole files correctly % 2004-09-08 Uses mp3info to get info about mp3 files too % 2004-09-18 Reports all mp3info fields in OPTS.fmt; handles MPG2LSF sizes % + added MONO, DOWNSAMP flags, changed default behavior. % 2005-09-28 Fixed bug reading full-rate stereo as 1ch (thx [email protected]) % 2006-09-17 Chop off initial 2257 sample delay (for 44.1 kHz mp3) % so read-write loop doesn't get progressively delayed. % You can suppress this with a 5th argument of 0. % 2007-02-04 Added support for FMT argument to match wavread % Added automatic selection of binary etc. to allow it % to work cross-platform without editing prior to % submitting to Matlab File Exchange % 2007-07-23 Tweaks to 'size' mode so it exactly agrees with read data. % 2009-03-15 Added fixes so 'http://...' file URLs will work. % 2009-03-26 Added filename length check to http: test (thx fabricio guzman) % find our baseline directory path = fileparts(which('mp3read')); % %%%%% Directory for temporary file (if needed) % % Try to read from environment, or use /tmp if it exists, or use CWD tmpdir = getenv('TMPDIR'); if isempty(tmpdir) || exist(tmpdir,'file')==0 tmpdir = '/tmp'; end if exist(tmpdir,'file')==0 tmpdir = ''; end % ensure it exists %if length(tmpdir) > 0 && exist(tmpdir,'file')==0 % mkdir(tmpdir); %end %%%%%% Command to delete temporary file (if needed) rmcmd = 'rm'; %%%%%% Location of the binaries - attempt to choose automatically %%%%%% (or edit to be hard-coded for your installation) ext = lower(computer); if ispc ext = 'exe'; rmcmd = 'del'; end % mpg123-0.59 inserts silence at the start of decoded files, which % we compensate. However, this is fixed in mpg123-1.9.0, so % make this flag 1 only if you have mpg123-0.5.9 MPG123059 = 0; mpg123 = '/usr/local/bin/mpg123'; %%%PJH %%%mpg123 = fullfile(path,['mpg123.',ext]); mp3info = '/usr/local/bin/mp3info'; %%%PJH %%%mp3info = fullfile(path,['mp3info.',ext]); %%%%% Check for network mode if length(FILE) > 6 && (strcmp(lower(FILE(1:7)),'http://') == 1 ... || strcmp(lower(FILE(1:6)),'ftp://')) % mp3info not available over network OVERNET = 1; else OVERNET = 0; end %%%%% Process input arguments if nargin < 2 N = 0; end % Check for FMT spec (per wavread) FMT = 'double'; if ischar(N) FMT = lower(N); N = 0; end if length(N) == 1 % Specified N was upper limit N = [1 N]; end if nargin < 3 forcemono = 0; else % Check for 3rd arg as FMT if ischar(MONO) FMT = lower(MONO); MONO = 0; end forcemono = (MONO ~= 0); end if nargin < 4 downsamp = 1; else downsamp = DOWNSAMP; end if downsamp ~= 1 && downsamp ~= 2 && downsamp ~= 4 error('DOWNSAMP can only be 1, 2, or 4'); end % process DELAY option (nargin 5) after we've read the SR if strcmp(FMT,'native') == 0 && strcmp(FMT,'double') == 0 && ... strcmp(FMT,'size') == 0 error(['FMT must be ''native'' or ''double'' (or ''size''), not ''',FMT,'''']); end %%%%%% Constants NBITS=16; %%%%% add extension if none (like wavread) [path,file,ext] = fileparts(FILE); if isempty(ext) FILE = [FILE, '.mp3']; end if ~OVERNET %%%%%% Probe file to find format, size, etc. using "mp3info" utility cmd = ['"',mp3info, '" -r m -p "%Q %u %b %r %v * %C %e %E %L %O %o %p" "', FILE,'"']; % Q = samprate, u = #frames, b = #badframes (needed to get right answer from %u) % r = bitrate, v = mpeg version (1/2/2.5) % C = Copyright, e = emph, E = CRC, L = layer, O = orig, o = mono, p = pad w = mysystem(cmd); % Break into numerical and ascii parts by finding the delimiter we put in starpos = findstr(w,'*'); nums = str2num(w(1:(starpos - 2))); strs = tokenize(w((starpos+2):end)); SR = nums(1); nframes = nums(2); nchans = 2 - strcmp(strs{6}, 'mono'); layer = length(strs{4}); bitrate = nums(4)*1000; mpgv = nums(5); % Figure samples per frame, after % http://board.mp3-tech.org/view.php3?bn=agora_mp3techorg&key=1019510889 if layer == 1 smpspfrm = 384; elseif SR < 32000 && layer ==3 smpspfrm = 576; if mpgv == 1 error('SR < 32000 but mpeg version = 1'); end else smpspfrm = 1152; end OPTS.fmt.mpgBitrate = bitrate; OPTS.fmt.mpgVersion = mpgv; % fields from wavread's OPTS OPTS.fmt.nAvgBytesPerSec = bitrate/8; OPTS.fmt.nSamplesPerSec = SR; OPTS.fmt.nChannels = nchans; OPTS.fmt.nBlockAlign = smpspfrm/SR*bitrate/8; OPTS.fmt.nBitsPerSample = NBITS; OPTS.fmt.mpgNFrames = nframes; OPTS.fmt.mpgCopyright = strs{1}; OPTS.fmt.mpgEmphasis = strs{2}; OPTS.fmt.mpgCRC = strs{3}; OPTS.fmt.mpgLayer = strs{4}; OPTS.fmt.mpgOriginal = strs{5}; OPTS.fmt.mpgChanmode = strs{6}; OPTS.fmt.mpgPad = strs{7}; OPTS.fmt.mpgSampsPerFrame = smpspfrm; else % OVERNET mode OPTS = []; % guesses smpspfrm = 1152; SR = 44100; nframes = 0; end if SR == 16000 && downsamp == 4 error('mpg123 will not downsample 16 kHz files by 4 (only 2)'); end % process or set delay if nargin < 5 if MPG123059 mpg123delay44kHz = 2257; % empirical delay of lame/mpg123 loop mpg123delay16kHz = 1105; % empirical delay of lame/mpg123 loop for 16 kHz sampling if SR == 16000 rawdelay = mpg123delay16kHz; else rawdelay = mpg123delay44kHz; % until we know better end delay = round(rawdelay/downsamp); else % seems like predelay is fixed in mpg123-1.9.0 delay = 0; end else delay = DELAY; end if downsamp == 1 downsampstr = ''; else downsampstr = [' -',num2str(downsamp)]; end FS = SR/downsamp; if forcemono == 1 nchans = 1; chansstr = ' -m'; else chansstr = ''; end % Size-reading version if strcmp(FMT,'size') == 1 Y = [floor(smpspfrm*nframes/downsamp)-delay, nchans]; else % Temporary file to use tmpfile = fullfile(tmpdir, ['tmp',num2str(round(1000*rand(1))),'.wav']); skipx = 0; skipblks = 0; skipstr = ''; sttfrm = N(1)-1; % chop off transcoding delay? %sttfrm = sttfrm + delay; % empirically measured % no, we want to *decode* those samples, then drop them % so delay gets added to skipx instead if sttfrm > 0 skipblks = floor(sttfrm*downsamp/smpspfrm); skipx = sttfrm - (skipblks*smpspfrm/downsamp); skipstr = [' -k ', num2str(skipblks)]; end skipx = skipx + delay; lenstr = ''; endfrm = -1; decblk = 0; if length(N) > 1 endfrm = N(2); if endfrm > sttfrm decblk = ceil((endfrm+delay)*downsamp/smpspfrm) - skipblks + 10; % we read 10 extra blks (+10) to cover the case where up to 10 bad % blocks are included in the part we are trying to read (it happened) lenstr = [' -n ', num2str(decblk)]; % This generates a spurious "Warn: requested..." if reading right % to the last sample by index (or bad blks), but no matter. end end % Run the decode cmd=['"',mpg123,'"', downsampstr, chansstr, skipstr, lenstr, ... ' -q -w "', tmpfile,'" "',FILE,'"']; %w = mysystem(cmd); % Load the data Y = wavread(tmpfile); % % pad delay on to end, just in case % Y = [Y; zeros(delay,size(Y,2))]; % % no, the saved file is just longer if decblk > 0 && length(Y) < decblk*smpspfrm/downsamp % This will happen if the selected block range includes >1 bad block disp(['Warn: requested ', num2str(decblk*smpspfrm/downsamp),' frames, returned ',num2str(length(Y))]); end % Delete tmp file mysystem([rmcmd,' "', tmpfile,'"']); % debug % disp(['sttfrm=',num2str(sttfrm),' endfrm=',num2str(endfrm),' skipx=',num2str(skipx),' delay=',num2str(delay),' len=',num2str(length(Y))]); % Select the desired part if skipx+endfrm-sttfrm > length(Y) endfrm = length(Y)+sttfrm-skipx; end disp(['PJH: mp3read.m: 01']); fflush(stdout); if endfrm > sttfrm disp(['PJH: mp3read.m: 02, CRAP!']); fflush(stdout); Y = Y(skipx+(1:(endfrm-sttfrm)),:); elseif skipx > 0 disp(['PJH: mp3read.m: 03, CRAP!']); fflush(stdout); Y = Y((skipx+1):end,:); end % Convert to int if format = 'native' if strcmp(FMT,'native') disp(['PJH: mp3read.m: 04, native']); fflush(stdout); Y = int16((2^15)*Y); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function w = mysystem(cmd) % Run system command; report error; strip all but last line [s,w] = system(cmd); if s ~= 0 error(['unable to execute ',cmd,' (',w,')']); end % Keep just final line w = w((1+max([0,findstr(w,10)])):end); % Debug %disp([cmd,' -> ','*',w,'*']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = tokenize(s,t) % Break space-separated string into cell array of strings. % Optional second arg gives alternate separator (default ' ') % 2004-09-18 [email protected] if nargin < 2; t = ' '; end a = []; p = 1; n = 1; l = length(s); nss = findstr([s(p:end),t],t); for ns = nss % Skip initial spaces (separators) if ns == p p = p+1; else if p <= l a{n} = s(p:(ns-1)); n = n+1; p = ns+1; end end end
github
martinarielhartmann/mirtooloct-master
convolve2.m
.m
mirtooloct-master/MIRToolbox/convolve2.m
7,776
utf_8
3946f147a02830e1954206f3fd2e961b
function y = convolve2(x, m, shape, tol) %CONVOLVE2 Two dimensional convolution. % Y = CONVOLVE2(X, M) performs the 2-D convolution of matrices X and % M. If [mx,nx] = size(X) and [mm,nm] = size(M), then size(Y) = % [mx+mm-1,nx+nm-1]. Values near the boundaries of the output array are % calculated as if X was surrounded by a border of zero values. % % Y = CONVOLVE2(X, M, SHAPE) where SHAPE is a string returns a % subsection of the 2-D convolution with size specified by SHAPE: % % 'full' - (default) returns the full 2-D convolution, % 'same' - returns the central part of the convolution % that is the same size as A (using zero padding), % 'valid' - returns only those parts of the convolution % that are computed without the zero-padded % edges, size(Y) = [mx-mm+1,nx-nm+1] when % size(X) > size(M), % 'wrap' - as for 'same' except that instead of using % zero-padding the input A is taken to wrap round as % on a toroid. % 'reflect' - as for 'same' except that instead of using % zero-padding the input A is taken to be reflected % at its boundaries. % % CONVOLVE2 is fastest when mx > mm and nx > nm - i.e. the first % argument is the input and the second is the mask. % % If the rank of the mask M is low, CONVOLVE2 will decompose it into a % sum of outer product masks, each of which is applied efficiently as % convolution with a row vector and a column vector, by calling CONV2. % The function will often be faster than CONV2 or FILTER2 (in some % cases much faster) and will produce the same results as CONV2 to % within a small tolerance. % % Y = CONVOLVE2(... , TOL) where TOL is a number in the range 0.0 to % 1.0 computes the convolution using a reduced-rank approximation to % M, provided this will speed up the computation. TOL limits the % relative sum-squared error in the effective mask; that is, if the % effective mask is E, the error is controlled such that % % sum(sum( (M-E) .* (M-E) )) % -------------------------- <= TOL % sum(sum( M .* M )) % % See also CONV2, FILTER2. % David Young, Department of Informatics, University of Sussex, February 2002, % revised January 2005. % Deal with optional arguments error(nargchk(2,4,nargin)); if nargin < 3 shape = 'full'; % shape default as for CONV2 tol = 0; elseif nargin < 4 if isnumeric(shape) tol = shape; shape = 'full'; else tol = 0; end end; % Set up to do the wrap & reflect operations, not handled by conv2 if strcmp(shape, 'wrap') x = wraparound(x, m); shape = 'valid'; elseif strcmp(shape, 'reflect') x = reflectborders(x, m); shape = 'valid'; end % do the convolution itself y = doconv(x, m, shape, tol); %----------------------------------------------------------------------- function y = doconv(x, m, shape, tol); % Carry out convolution [mx, nx] = size(x); [mm, nm] = size(m); % If the mask is bigger than the input, or it is 1-D already, % just let CONV2 handle it. if mm > mx | nm > nx | mm == 1 | nm == 1 y = conv2(x, m, shape); else % Get svd of mask if mm < nm; m = m'; end % svd(..,0) wants m > n [u,s,v] = svd(m, 0); s = diag(s); rank = trank(m, s, tol); if rank*(mm+nm) < mm*nm % take advantage of low rank if mm < nm; t = u; u = v; v = t; end % reverse earlier transpose vp = v'; % For some reason, CONV2(H,C,X) is very slow, so use the normal call y = conv2(conv2(x, u(:,1)*s(1), shape), vp(1,:), shape); for r = 2:rank y = y + conv2(conv2(x, u(:,r)*s(r), shape), vp(r,:), shape); end else if mm < nm; m = m'; end % reverse earlier transpose y = conv2(x, m, shape); end end %----------------------------------------------------------------------- function r = trank(m, s, tol) % Approximate rank function - returns rank of matrix that fits given % matrix to within given relative rms error. Expects original matrix % and vector of singular values. if tol < 0 | tol > 1 error('Tolerance must be in range 0 to 1'); end if tol == 0 % return estimate of actual rank tol = length(m) * max(s) * eps; r = sum(s > tol); else ss = s .* s; t = (1 - tol) * sum(ss); r = 0; sm = 0; while sm < t r = r + 1; sm = sm + ss(r); end end %----------------------------------------------------------------------- function y = wraparound(x, m) % Extend x so as to wrap around on both axes, sufficient to allow a % "valid" convolution with m to return the cyclical convolution. % We assume mask origin near centre of mask for compatibility with % "same" option. [mx, nx] = size(x); [mm, nm] = size(m); if mm > mx | nm > nx error('Mask does not fit inside array') end mo = floor((1+mm)/2); no = floor((1+nm)/2); % reflected mask origin ml = mo-1; nl = no-1; % mask left/above origin mr = mm-mo; nr = nm-no; % mask right/below origin me = mx-ml+1; ne = nx-nl+1; % reflected margin in input mt = mx+ml; nt = nx+nl; % top of image in output my = mx+mm-1; ny = nx+nm-1; % output size y = zeros(my, ny); y(mo:mt, no:nt) = x; % central region if ml > 0 y(1:ml, no:nt) = x(me:mx, :); % top side if nl > 0 y(1:ml, 1:nl) = x(me:mx, ne:nx); % top left corner end if nr > 0 y(1:ml, nt+1:ny) = x(me:mx, 1:nr); % top right corner end end if mr > 0 y(mt+1:my, no:nt) = x(1:mr, :); % bottom side if nl > 0 y(mt+1:my, 1:nl) = x(1:mr, ne:nx); % bottom left corner end if nr > 0 y(mt+1:my, nt+1:ny) = x(1:mr, 1:nr); % bottom right corner end end if nl > 0 y(mo:mt, 1:nl) = x(:, ne:nx); % left side end if nr > 0 y(mo:mt, nt+1:ny) = x(:, 1:nr); % right side end %----------------------------------------------------------------------- function y = reflectborders(x, m) % Extend x so as to reflect at each boundary, sufficient to allow a % "valid" convolution with m to return a matrix the same size as % the orginal. % We assume mask origin near centre of mask for compatibility with % "same" option. [mx, nx] = size(x); [mm, nm] = size(m); if mm > mx | nm > nx error('Mask does not fit inside array') end mo = floor((1+mm)/2); no = floor((1+nm)/2); % reflected mask origin ml = mo-1; nl = no-1; % mask left/above origin mr = mm-mo; nr = nm-no; % mask right/below origin me = mx-mr+1; ne = nx-nr+1; % translated margin in input mt = mx+ml; nt = nx+nl; % top/right of image in output my = mx+mm-1; ny = nx+nm-1; % output size y = zeros(my, ny); y(mo:mt, no:nt) = x; % central region if ml > 0 y(1:ml, no:nt) = x(ml:-1:1, :); % top side if nl > 0 y(1:ml, 1:nl) = x(ml:-1:1, nl:-1:1); % top left corner end if nr > 0 y(1:ml, nt+1:ny) = x(ml:-1:1, nx:-1:ne); % top right corner end end if mr > 0 y(mt+1:my, no:nt) = x(mx:-1:me, :); % bottom side if nl > 0 y(mt+1:my, 1:nl) = x(mx:-1:me, nl:-1:1); % bottom left corner end if nr > 0 y(mt+1:my, nt+1:ny) = x(mx:-1:me, nx:-1:ne); % bottom right corner end end if nl > 0 y(mo:mt, 1:nl) = x(:, nl:-1:1); % left side end if nr > 0 y(mo:mt, nt+1:ny) = x(:, nx:-1:ne); % right side end
github
martinarielhartmann/mirtooloct-master
mirkurtosis.m
.m
mirtooloct-master/MIRToolbox/mirkurtosis.m
1,110
utf_8
a1f7b0edb45216089fdc8d17f29fa799
function varargout = mirkurtosis(orig,varargin) % k = mirkurtosis(x) calculates the kurtosis of x, indicating whether % the curve is peaked or flat relative to a normal distribution. % x can be either: % - a spectrum (spectral kurtosis), % - an envelope (temporal kurtosis), or % - any histogram. varargout = mirfunction(@mirkurtosis,orig,varargin,nargout,struct,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirdata')) || isamir(x,'miraudio') x = mirspectrum(x); end type = 'mirscalar'; function k = main(x,option,postoption) if iscell(x) x = x{1}; end y = peaksegments(@kurtosis,get(x,'Data'),... get(x,'Pos'),... get(mircentroid(x,'MaxEntropy',0),'Data'),... get(mirspread(x),'Data')); if isa(x,'mirspectrum') t = 'Spectral kurtosis'; elseif isa(x,'mirenvelope') t = 'Temporal kurtosis'; else t = ['Kurtosis of ',get(x,'Title')]; end k = mirscalar(x,'Data',y,'Title',t,'Unit',''); function k = kurtosis(d,p,c,s) k = sum((p-c).^4.*(d/sum(d))) ./ s.^4;
github
martinarielhartmann/mirtooloct-master
mirflux.m
.m
mirtooloct-master/MIRToolbox/mirflux.m
14,091
utf_8
9718f5621e82c5f247eeea63a085f39f
function varargout = mirflux(orig,varargin) % f = mirflux(x) measures distance between successive frames. % First argument: % If x is a spectrum, this corresponds to spectral flux. % But the flux of any other data can be computed as well. % If x is an audio file or audio signal, the spectral flux is % computed by default. % Optional arguments: % f = mirflux(x,'Frame',...) specifies the frame parameters, if x is % not already decomposed into frames. Default values are frame % length of .2 seconds and hop factor of 1.3. % f = mirflux(x,'Dist',d) specifies the distance between % successive frames: (IF 'COMPLEX': DISTANCE = 'CITY' ALWAYS) % d = 'Euclidian': Euclidian distance (Default) % d = 'City': City-block distance % d = 'Cosine': Cosine distance (or normalized correlation) % f = mirflux(...,'Inc'): Only positive difference between frames are % summed, in order to focus on increase of energy solely. % f = mirflux(...,'Complex'), for spectral flux, combines use of % energy and phase information (Bello et al, 2004). % f = mirflux(...,'Halfwave'): performs a half-wave rectification on % the result. % f = mirflux(...,'Median',l,C): removes small spurious peaks by % subtracting to the result its median filtering. The median % filter computes the point-wise median inside a window of length % l (in seconds), that includes a same number of previous and % next samples. C is a scaling factor whose purpose is to % artificially rise the curve slightly above the steady state of % the signal. If no parameters are given, the default values are: % l = 0.2 s. and C = 1.3 % f = mirflux(...,'Median',l,C,'Halfwave'): The scaled median % filtering is designed to be succeeded by the half-wave % rectification process in order to select peaks above the % dynamic threshold calculated with the help of the median % filter. The resulting signal is called "detection function" % (Alonso, David, Richard, 2004). To ensure accurate detection, % the length l of the median filter must be longer than the % average width of the peaks of the detection function. % % (Bello et al, 2004) Juan P. Bello, Chris Duxbury, Mike Davies, and Mark % Sandler, On the Use of Phase and Energy for Musical Onset Detection in % the Complex Domain, IEEE SIGNAL PROCESSING LETTERS, VOL. 11, NO. 6, % JUNE 2004 dist.key = 'Dist'; dist.type = 'String'; dist.default = 'Euclidean'; option.dist = dist; inc.key = 'Inc'; inc.type = 'Boolean'; inc.default = 0; option.inc = inc; bs.key = 'BackSmooth'; bs.type = 'String'; bs.choice = {'Goto','Lartillot'}; bs.default = ''; bs.keydefault = 'Goto';%'Lartillot';%'Goto';% option.bs = bs; complex.key = 'Complex'; complex.type = 'Boolean'; complex.default = 0; option.complex = complex; gap.key = 'Gaps'; gap.type = 'Integer'; gap.default = 0; gap.keydefault = .2; option.gap = gap; sb.key = 'SubBand'; sb.type = 'String'; sb.choice = {'Gammatone','2Channels','Manual'}; sb.default = ''; sb.keydefault = 'Manual'; option.sb = sb; h.key = 'Halfwave'; h.type = 'Boolean'; h.default = 0; h.when = 'After'; option.h = h; median.key = 'Median'; median.type = 'Integer'; median.number = 2; median.default = [0 0]; median.keydefault = [.2 1.3]; median.when = 'After'; option.median = median; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [.05 .5]; option.frame = frame; specif.option = option; varargout = mirfunction(@mirflux,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if ~isempty(option.sb) if strcmpi(option.sb,'Manual') x = mirfilterbank(x,'Manual',[-Inf 50*2.^(0:1:8) Inf],'Order',2); else x = mirfilterbank(x,option.sb); end end if isamir(x,'miraudio') if isframed(x) x = mirspectrum(x); else x = mirspectrum(x,'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend); end end if isa(x,'mirdesign') if strcmpi(option.bs,'Goto') x = set(x,'Overlap',2); else x = set(x,'Overlap',1); end end type = 'mirscalar'; function f = main(s,option,postoption) if iscell(s) s = s{1}; end t = get(s,'Title'); if isa(s,'mirscalar') && ... (strcmp(t,'Harmonic Change Detection Function') || ... (length(t)>4 && strcmp(t(end-3:end),'flux')) || ... (length(t)>5 && strcmp(t(end-4:end-1),'flux'))) if not(isempty(postoption)) f = modif(s,postoption); end else if isa(s,'mirspectrum') t = 'Spectral'; end m = get(s,'Data'); if option.complex if not(isa(s,'mirspectrum')) error('ERROR IN MIRFLUX: ''Complex'' option only defined for spectral flux.'); end ph = get(s,'Phase'); end param.complex = option.complex; param.inc = option.inc; fp = get(s,'FramePos'); if strcmp(t,'Tonal centroid') t = 'Harmonic Change Detection Function'; else t = [t,' flux']; end %disp(['Computing ' t '...']) ff = cell(1,length(m)); newsr = cell(1,length(m)); dist = str2func(option.dist); if option.bs [tmp s] = gettmp(s); end for h = 1:length(m) ff{h} = cell(1,length(m{h})); if not(iscell(m{h})) m{h} = {m{h}}; end for i = 1:length(m{h}) mi = m{h}{i}; if size(mi,3) > 1 && size(mi,1) == 1 mi = reshape(mi,size(mi,2),size(mi,3))'; end if strcmpi(option.bs,'Lartillot') mi = mi + 120; %- min(min(min(mi))); end if option.complex phi = ph{h}{i}; end fpi = fp{h}{i}; nc = size(mi,2); np = size(mi,3); if nc == 1 warning('WARNING IN MIRFLUX: Flux can only be computed on signal decomposed into frames.'); ff{h}{i} = []; else if option.complex fl = zeros(1,nc-2,np); for k = 1:np d = diff(phi(:,:,k),2,2); d = d/(2*pi) - round(d/(2*pi)); g = sqrt(mi(:,3:end,k).^2 + mi(:,2:(end-1),k).^2 ... - 2.*mi(:,3:end,k)... .*mi(:,2:(end-1),k)... .*cos(d)); fl(1,:,k) = sum(g); end fp{h}{i} = fpi(:,3:end); else if strcmpi(option.bs,'Goto') limit = nc-2; else limit = nc-1; end fl = zeros(1,limit,np); if option.gap mimi = min(min(mi)); mi = (mi - mimi)/(max(max(mi)) - mimi); end for k = 1:np if option.gap for j = 1:nc-1 fl(1,j,k) = detectgap(mi(:,j,k),... mi(:,j+1,k),... option.gap); end elseif ~isempty(option.bs) p = get(s,'Pos'); res = diff(p{1}{1}(1:2)); if strcmpi(option.bs,'Goto') l = round(43/res); else l = round(17/res); end memo = 4;%; 50; if isempty(tmp) tmp = -Inf(size(mi,1),memo-1,np); end mi = [tmp mi]; mi2 = mi; if 0 bk = zeros(size(mi)); bs = zeros(size(mi)); end for j = 1:limit mj = mi(:,j+memo-1,k); mj2 = zeros(length(mj)-l,l-1); for j2 = 1:l-1 mj2(:,j2) = mj(j2:j2+length(mj)-l-1); end mj(1+floor(l/2):end-ceil(l/2)) = max(mj2,[],2); ... %max(mj(1:end-l),mj(1+l:end)); mi2(:,j+memo-1,k) = mj; if strcmpi(option.bs,'Goto') back = max(mj,mi(:,j+memo-2,k)); else back = max(mi2(:,j:j+memo-1,k),[],2); end if 0 bk(:,j+1) = back; fbs = find(mi(:,j+memo,k) > back); bs(fbs,j+1) = mi(fbs,j+memo,k); end if strcmpi(option.bs,'Goto') forth = mi(:,j+memo+1,k); forth(1+floor(l/2):end-ceil(l/2)) = ... min(forth(1:end-l),forth(1+l:end)); fl(1,j,k) = Goto(back,mi(:,j+memo,k),forth,mi(:,j+memo+1,k)); else fl(1,j,k) = dist(back,mi(:,j+memo,k)); end if 0 figure%(1) %hold off plot(mi2(:,j+memo-1,k)) hold on plot(back,'r') plot(mi(:,j+memo,k),'k') %figure(2) %plot(mean(fp{h}{i}(:,1:j)),fl(1,1:j,k)) %drawnow end end elseif option.inc for j = 1:nc-1 back = mi(:,j,k); fl(1,j,k) = dist(back,mi(:,j+1,k),1); end else for j = 1:nc-1 fl(1,j,k) = pdist(mi(:,[j j+1],k)',... option.dist); end end end end if option.complex || strcmpi(option.bs,'Goto') fp{h}{i} = fpi(:,2:end-1); else fp{h}{i} = fpi(:,2:end); end ff{h}{i} = fl; end end if size(fpi,2)<2 newsr{h} = 0; else newsr{h} = 1/(fpi(1,2)-fpi(1,1)); end end f = mirscalar(s,'Data',ff,'FramePos',fp,'Sampling',newsr,... 'Title',t,'Parameter',param); if not(isequal(postoption,struct)) f = modif(f,postoption); end if ~isempty(option.bs) && nc > 1 tmp = mi2(:,max(1,end-memo+1):end-1,k); f = settmp(f,tmp); end end function f = modif(f,option) fl = get(f,'Data'); r = get(f,'Sampling'); for h = 1:length(fl) for i = 1:length(fl{h}) fli = fl{h}{i}; nc = size(fli,2); np = size(fli,3); if option.median(1) ffi = zeros(1,nc,np); lr = round(option.median(1)*r{i}); for k = 1:np for j = 1:nc ffi(:,j,k) = fli(:,j,k) - ... option.median(2) * median(fli(:,max(1,j-lr):min(nc-1,j+lr),k)); end end fli = ffi; end if option.h fli = hwr(fli); end fl{h}{i} = fli; end end f = set(f,'Data',fl); function y = Euclidean(mi,mj,inc) if inc y = sqrt(sum(max(0,(mj-mi)).^2)); else y = sqrt(sum((mj-mi).^2)); end function y = City(mi,mj,inc) if inc y = sum(max(0,(mj-mi))); else y = sum(abs(mj-mi)); end function y = Gate(mi,mj,inc) y = sum(mj .* (mj>mi)); %max? %y = sum(max(mj-mi,0)); function y = Goto(mi,mj,mk,mk2) %y = sum(max(mj,mk2) .* (mj>mi).* (mk>mi)); y = sum( (max(mj,mk2) - mi) .* (mj>mi).* (mk>mi)); %function y = NewGate(mi,mj,inc) %N = 9; %M = zeros(length(mi)-N+1,N); %for i = 1:N % M(:,i) = mi(i:end-(N-i)); %end %mj0 = mj(ceil(N/2):end-floor(N/2)); %y = abs(repmat(mj0,[1 N]) - M); %y = min(y,[],2); %y = sum(y); %.*mj0); function d = Cosine(r,s,inc) % inc does not work here! nr = sqrt(r'*r); ns = sqrt(s'*s); if or(nr == 0, ns == 0); d = 1; else d = 1 - r'*s/nr/ns; end function d = detectgap(mi,mj,thr) d = length(find(abs(mi-mj)>thr)) / length(mi);
github
martinarielhartmann/mirtooloct-master
isamir.m
.m
mirtooloct-master/MIRToolbox/isamir.m
1,010
utf_8
9284a4ea4a0c048ce4ff9e16c746bbcc
function b = isamir(x,class) if isempty(x) || isnumeric(x) b = 0; return end if iscell(x) x = x{1}; end if isa(x,class) b = 1; return elseif ischar(x) && strcmpi(class,'miraudio') b = 1; return elseif not(isa(x,'mirdesign')) b = 0; return end type = get(x,'Type'); if iscell(type) type = type{1}; end types = lineage(type); b = 0; i = 0; while not(b) && i<length(types) i = i+1; if strcmpi(types(i),class) b = 1; end end function types = lineage(class) switch class case {'miraudio','mirenvelope'} parent = 'mirtemporal'; case {'mirautocor','mircepstrum','mirchromagram','mirhisto',... 'mirkeysom','mirkeystrength','mirmatrix','mirmfcc',... 'mirscalar','mirsimatrix','mirspectrum',... 'mirtemporal','mirtonalcentroid'} parent = 'mirdata'; otherwise parent = ''; end if isempty(parent) types = {class}; else parents = lineage(parent); types = {class parents{:}}; end
github
martinarielhartmann/mirtooloct-master
mirskewness.m
.m
mirtooloct-master/MIRToolbox/mirskewness.m
1,074
utf_8
364ec04fe20b324d19216272e36dbe4e
function varargout = mirskewness(orig,varargin) % s = skewness(x) calculates the skewness of x, showing the (lack of) % symmetry of the curve. % x can be either: % - a spectrum (spectral skewness), % - an envelope (temporal skewness), or % - any histogram. varargout = mirfunction(@mirskewness,orig,varargin,nargout,struct,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirdata')) || isamir(x,'miraudio') x = mirspectrum(x); end type = 'mirscalar'; function s = main(x,option,postoption) if iscell(x) x = x{1}; end y = peaksegments(@skewness,get(x,'Data'),... get(x,'Pos'),... get(mircentroid(x,'MaxEntropy',0),'Data'),... get(mirspread(x),'Data')); if isa(x,'mirspectrum') t = 'Spectral skewness'; elseif isa(x,'mirenvelope') t = 'Temporal skewness'; else t = ['Skewness of ',get(x,'Title')]; end s = mirscalar(x,'Data',y,'Title',t,'Unit',''); function s = skewness(d,p,c,sp) s = sum((p-c).^3.* (d/sum(d)) ) ./ sp.^3;
github
martinarielhartmann/mirtooloct-master
mirattackleap.m
.m
mirtooloct-master/MIRToolbox/mirattackleap.m
1,995
utf_8
e307b35dab8a2b6e3325a4d18ab9a86c
function varargout = mirattackleap(orig,varargin) % a = mirattackleap(x) estimates the leap of each note attack. % Values are expressed in the same scale than the original signal. % Optional arguments: % mirattackleap(...,'Contrast',c) specifies the 'Contrast' parameter % used in mironsets for event detection through peak picking. % Same default value as in mironsets. % mirattackleap(...,'Single') only selects one attack phase in the signal % (or in each segment). cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = NaN; option.cthr = cthr; single.key = 'Single'; single.type = 'Boolean'; single.default = 0; option.single = single; log.key = 'LogOnset'; log.type = 'Boolean'; log.default = 0; option.log = log; minlog.key = 'MinLog'; minlog.type = 'Integer'; minlog.default = 0; option.minlog = minlog; specif.option = option; varargout = mirfunction(@mirattackleap,orig,varargin,nargout,specif,@init,@main); function [o type] = init(x,option) o = mironsets(x,'Attack','Contrast',option.cthr,'Single',option.single,... 'Log',option.log,'MinLog',option.minlog,... 'Filter','Normal','AcrossSegments'); type = mirtype(x); function sl = main(o,option,postoption) if iscell(o) o = o{1}; end po = get(o,'PeakPos'); pa = get(o,'AttackPos'); pou = get(o,'PeakPosUnit'); pau = get(o,'AttackPosUnit'); d = get(o,'Data'); sl = mircompute(@algo,po,pa,d); fp = mircompute(@frampose,pau,pou); sl = mirscalar(o,'Data',sl,'FramePos',fp,'Title','Attack Leap'); sl = {sl,o}; function fp = frampose(pa,po) if isempty(pa) fp = []; return end pa = sort(pa{1}); po = sort(po{1}); fp = [pa(:)';po(:)']; function lp = algo(po,pa,d) if isempty(pa) lp = []; return end pa = sort(pa{1}); po = sort(po{1}); lp = zeros(1,length(pa)); for i = 1:length(pa) lp(i) = (d(po(i))-d(pa(i))); end
github
martinarielhartmann/mirtooloct-master
mirfilterbank.m
.m
mirtooloct-master/MIRToolbox/mirfilterbank.m
13,869
utf_8
6dabae33d58255019308b5808ca8d34f
function varargout = mirfilterbank(orig,varargin) % b = mirfilterbank(x) performs a filterbank decomposition of an audio % waveform. % Optional arguments: % mirfilterbank(...,t) selects a type of filterbank. % Possible values: % t = 'Gammatone' (default for audio files). % Requires the Auditory Toolbox. % mirfilterbank(...,'Lowest',f): lowest frequency in Hz % (default: 50) % t = '2Channels' proposed in (Tolonen & Karjalainen, 2000) % mirfilterbank(...,'NbChannels',N), or simply filterbank(x,N): % specifies the number of channels in the bank. % (default: N = 10) % mirfilterbank(...,'Channel',c) only output the channels whose % ranks are indicated in the array c. % (default: c = (1:N)) % mirfilterbank(...,'Manual',f) specifies a set of low-pass, band- % pass and high-pass eliptic filters (Scheirer, 1998). % The series of cut-off frequencies as to be specified % as next parameter f. % If this series of frequencies f begins with -Inf, % the first filter is low-pass. % If this series of frequencies f ends with Inf, % the last filter is high-pass. % mirfilterbank(...,'Order',o) specifies the order of the filter. % (Default: o = 4) (Scheirer, 1998) % mirfilterbank(...,'Hop',h) specifies the degree of spectral % overlapping between successive channels. % If h = 1 (default value), the filters are non-overlapping. % If h = 2, the filters are half-overlapping. % If h = 3, the spectral hop factor between successive % filters is a third of the whole frequency region, etc. % mirfilterbank(...,p) specifies predefined filterbanks, all % implemented using elliptic filters, by default of order 4. % Possible values: % p = 'Mel' (mel-scale) % p = 'Bark' (bark-scale) % p = 'Scheirer' proposed in (Scheirer, 1998) corresponds to % 'Manual',[-Inf 200 400 800 1600 3200 Inf] % p = 'Klapuri' proposed in (Klapuri, 1999) corresponds to % 'Manual',44*[2.^ ([ 0:2, ( 9+(0:17) )/3 ]) ] nCh.key = 'NbChannels'; nCh.type = 'Integer'; nCh.default = 10; option.nCh = nCh; Ch.key = {'Channel','Channels'}; Ch.type = 'Integer'; Ch.default = 0; option.Ch = Ch; lowF.key = 'Lowest'; lowF.type = 'Integer'; lowF.default = 50; option.lowF = lowF; freq.key = 'Manual'; freq.type = 'Integer'; freq.default = NaN; option.freq = freq; overlap.key = 'Hop'; overlap.type = 'Boolean'; overlap.default = 1; option.overlap = overlap; filtertype.type = 'String'; filtertype.choice = {'Gammatone','2Channels',0}; filtertype.default = 'Gammatone'; option.filtertype = filtertype; filterorder.key = 'Order'; filterorder.type = 'Integer'; filterorder.default = 4; option.filterorder = filterorder; presel.type = 'String'; presel.choice = {'Scheirer','Klapuri','Mel','Bark'}; presel.default = ''; option.presel = presel; specif.option = option; specif.eachchunk = @eachchunk; specif.combinechunk = @combinechunk; varargout = mirfunction(@mirfilterbank,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'miraudio'; function b = main(x,option,postoption) if iscell(x) x = x{1}; end if ~isamir(x,'miraudio') mirerror('MIRFILTERBANK','The input should be an audio waveform.'); end f = get(x,'Sampling'); if strcmpi(option.presel,'Scheirer') option.freq = [-Inf 200 400 800 1600 3200 Inf]; elseif strcmpi(option.presel,'Klapuri') option.freq = 44*[2.^([0:2,(9+(0:17))/3])]; elseif strcmpi(option.presel,'Mel') lowestFrequency = 133.3333; linearFilters = 13; linearSpacing = 66.66666666; logFilters = 27; logSpacing = 1.0711703; totalFilters = linearFilters + logFilters; cepstralCoefficients = 13; option.freq = lowestFrequency + (0:linearFilters-1)*linearSpacing; option.freq(linearFilters+1:totalFilters+2) = ... option.freq(linearFilters) * logSpacing.^(1:logFilters+2); option.overlap = 2; elseif strcmpi(option.presel,'Bark') option.freq = [10 20 30 40 51 63 77 92 108 127 148 172 200 232 ... 270 315 370 440 530 640 770 950 1200 1550]*10; %% Hz end if not(isnan(option.freq)) option.filtertype = 'Manual'; end d = get(x,'Data'); if size(d{1}{1},3) > 1 warning('WARNING IN MIRFILTERBANK: The input data is already decomposed into channels. No more channel decomposition.'); if option.Ch cx = get(x,'Channels'); db = cell(1,length(d)); for k = 1:length(d) db{k} = cell(1,length(d{k})); for l = 1:length(d{k}) for i = 1:length(option.Ch) db{k}{l}(:,:,i) = d{k}{l}(:,:,find(cx{k} == option.Ch(i))); end end end b = set(x,'Data',db,'Channels',option.Ch); else b = x; end else i = 1; while i <= length(d) if size(d{i}{1},2) > 1 warning('WARNING IN MIRFILTERBANK: The frame decomposition should be performed after the filterbank decomposition.'); disp(['Suggestion: Use the ' char(34) 'Frame' char(34) ' option available to some of the MIRtoolbox functions.']) break end i = i+1; end nCh = option.nCh; Ch = option.Ch; [tmp x] = gettmp(x); output = cell(1,length(d)); nch = cell(1,length(d)); for i = 1:length(d) if isempty(tmp) %% Determination of the filterbank specifications if strcmpi(option.filtertype,'Gammatone') if not(Ch) Ch = 1:nCh; end Hd = ERBFilters(f{i},nCh,Ch,option.lowF); nch{i} = Ch; elseif strcmpi(option.filtertype,'2Channels') if not(Ch) Ch = 1:2; end [bl,al] = butter(4,[70 1000]/f{i}*2); if ismember(1,Ch) Hd{1} = dfilt.df2t(bl,al); k = 2; else k = 1; end if ismember(2,Ch) if f{i} < 20000 [bh,ah] = butter(2,1000/f{i}*2,'high'); else [bh,ah] = butter(2,[1000 10000]/f{i}*2); end Hd{k} = {dfilt.df2t(bl,al),... @(x) max(x,0),... dfilt.df2t(bh,ah)}; end nch{i} = Ch; elseif strcmpi(option.filtertype,'Manual') freqi = option.freq; j = 1; while j <= length(freqi) if not(isinf(freqi(j))) && freqi(j)>f{i}/2 if j == length(freqi) freqi(j) = Inf; else freqi(j) = []; j = j-1; end end j = j+1; end step = option.overlap; for j = 1:length(freqi)-step if isinf(freqi(j)) [z{j},p{j},k{j}] = ellip(option.filterorder,3,40,... freqi(j+step)/f{i}*2); elseif isinf(freqi(j+step)) [z{j},p{j},k{j}] = ellip(option.filterorder,3,40,... freqi(j)/f{i}*2,'high'); else [z{j},p{j},k{j}] = ellip(option.filterorder,3,40,... freqi([j j+step])/f{i}*2); end end for j = 1:length(z) [sos,g] = zp2sos(z{j},p{j},k{j}); Hd{j} = dfilt.df2tsos(sos,g); end nch{i} = 1:length(freqi)-step; end if length(d) == 1 for k = 1:length(Hd) Hdk = Hd{k}; if ~iscell(Hdk) Hdk = {Hdk}; end for h = 1:length(Hdk) if ~isa(Hdk{h},'function_handle') Hdk{h}.PersistentMemory = true; end end end end elseif i == 1 Hd = tmp; end output{i} = cell(1,length(d{i})); for j = 1:length(d{i}) for k = 1:length(Hd) dk = d{i}{j}; Hdk = Hd{k}; if ~iscell(Hdk) Hdk = {Hdk}; end for h = 1:length(Hdk) if isa(Hdk{h},'function_handle') dk = Hdk{h}(dk); else dk = Hdk{h}.filter(dk); end end output{i}{j}(:,:,k) = dk; end end end b = set(x,'Data',output,'Channels',nch); b = settmp(b,Hd); end %% function Hd=ERBFilters(fs,numChannels,chans,lowFreq) % This function computes the filter coefficients for a bank of % Gammatone filters. These filters were defined by Patterson and % Holdworth for simulating the cochlea. % The transfer function of these four second order filters share the same % denominator (poles) but have different numerators (zeros). % The filter bank contains "numChannels" channels that extend from % half the sampling rate (fs) to "lowFreq". % Note this implementation fixes a problem in the original code by % computing four separate second order filters. This avoids a big % problem with round off errors in cases of very small cfs (100Hz) and % large sample rates (44kHz). The problem is caused by roundoff error % when a number of poles are combined, all very close to the unit % circle. Small errors in the eigth order coefficient, are multiplied % when the eigth root is taken to give the pole location. These small % errors lead to poles outside the unit circle and instability. Thanks % to Julius Smith for leading me to the proper explanation. % Code taken from Auditory Toolbox and optimized. % (Malcolm Slaney, August 1993, (c) 1998 Interval Research Corporation) T = 1/fs; EarQ = 9.26449; % Glasberg and Moore Parameters minBW = 24.7; %% % Computes an array of numChannels frequencies uniformly spaced between % fs/2 and lowFreq on an ERB scale. % % For a definition of ERB, see Moore, B. C. J., and Glasberg, B. R. (1983). % "Suggested formulae for calculating auditory-filter bandwidths and % excitation patterns," J. Acoust. Soc. Am. 74, 750-753. % % Derived from Apple TR #35, "An % Efficient Implementation of the Patterson-Holdsworth Cochlear % Filter Bank." See pages 33-34. cf = -(EarQ*minBW) + exp((1:numChannels)'*(-log(fs/2 + EarQ*minBW) + ... log(lowFreq + EarQ*minBW))/numChannels) * (fs/2 + EarQ*minBW); %% ERB = ((cf/EarQ) + minBW); B=1.019*2*pi*ERB; A0 = T; A2 = 0; B0 = 1; B1 = -2*cos(2*cf*pi*T)./exp(B*T); B2 = exp(-2*B*T); A11 = -(2*T*cos(2*cf*pi*T)./exp(B*T) + 2*sqrt(3+2^1.5)*T*sin(2*cf*pi*T)./ ... exp(B*T))/2; A12 = -(2*T*cos(2*cf*pi*T)./exp(B*T) - 2*sqrt(3+2^1.5)*T*sin(2*cf*pi*T)./ ... exp(B*T))/2; A13 = -(2*T*cos(2*cf*pi*T)./exp(B*T) + 2*sqrt(3-2^1.5)*T*sin(2*cf*pi*T)./ ... exp(B*T))/2; A14 = -(2*T*cos(2*cf*pi*T)./exp(B*T) - 2*sqrt(3-2^1.5)*T*sin(2*cf*pi*T)./ ... exp(B*T))/2; gain = abs((-2*exp(4i*cf*pi*T)*T + ... 2*exp(-(B*T) + 2i*cf*pi*T).*T.* ... (cos(2*cf*pi*T) - sqrt(3 - 2^(3/2))* ... sin(2*cf*pi*T))) .* ... (-2*exp(4i*cf*pi*T)*T + ... 2*exp(-(B*T) + 2i*cf*pi*T).*T.* ... (cos(2*cf*pi*T) + sqrt(3 - 2^(3/2)) * ... sin(2*cf*pi*T))).* ... (-2*exp(4i*cf*pi*T)*T + ... 2*exp(-(B*T) + 2i*cf*pi*T).*T.* ... (cos(2*cf*pi*T) - ... sqrt(3 + 2^(3/2))*sin(2*cf*pi*T))) .* ... (-2*exp(4i*cf*pi*T)*T + 2*exp(-(B*T) + 2i*cf*pi*T).*T.* ... (cos(2*cf*pi*T) + sqrt(3 + 2^(3/2))*sin(2*cf*pi*T))) ./ ... (-2 ./ exp(2*B*T) - 2*exp(4i*cf*pi*T) + ... 2*(1 + exp(4i*cf*pi*T))./exp(B*T)).^4); allfilts = ones(length(cf),1); A0 = A0*allfilts; A2 = A2*allfilts; B0 = B0*allfilts; for i = 1:length(chans) chan = length(gain)-chans(i)+1; % Revert the channels order aa1 = [A0(chan)/gain(chan) A11(chan)/gain(chan) A2(chan)/gain(chan)]; bb1 = [B0(chan) B1(chan) B2(chan)]; aa2 = [A0(chan) A12(chan) A2(chan)]; bb2 = [B0(chan) B1(chan) B2(chan)]; aa3 = [A0(chan) A13(chan) A2(chan)]; bb3 = [B0(chan) B1(chan) B2(chan)]; aa4 = [A0(chan) A14(chan) A2(chan)]; bb4 = [B0(chan) B1(chan) B2(chan)]; Hd{i} = {dfilt.df2t(aa1,bb1);dfilt.df2t(aa2,bb2);... dfilt.df2t(aa3,bb3);dfilt.df2t(aa4,bb4)}; end %% function [y orig] = eachchunk(orig,option,missing) y = mirfilterbank(orig,option); function y = combinechunk(old,new) doo = get(old,'Data'); to = get(old,'Time'); dn = get(new,'Data'); tn = get(new,'Time'); y = set(old,'Data',{{[doo{1}{1};dn{1}{1}]}},... 'Time',{{[to{1}{1};tn{1}{1}]}});
github
martinarielhartmann/mirtooloct-master
mirharmonicity.m
.m
mirtooloct-master/MIRToolbox/mirharmonicity.m
2,940
utf_8
ba5a2677382e4fe554d91904f000d2d3
function varargout = mirharmonicity(orig,varargin) frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [.1 .025]; option.frame = frame; specif.option = option; varargout = mirfunction(@mirharmonicity,orig,varargin,nargout,specif,@init,@main); function [i type] = init(x,option) if isamir(x,'miraudio') if option.frame.length.val s = mirspectrum(x,'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend); else s = mirspectrum(x); end else s = x; end p = mirpeaks(s,'Harmonic',20,'Contrast',.01); i = {s,p}; type = {'mirscalar','mirscalar','mirscalar','mirspectrum'}; function h = main(x,option,postoption) s = x{1}; p = x{2}; if iscell(p) p = p{1}; end m = get(s,'Magnitude'); f = get(s,'Frequency'); pf = get(p,'TrackPos'); he = cell(1,length(m)); ie = cell(1,length(m)); hi = cell(1,length(m)); for h = 1:length(m) he{h} = cell(1,length(m{h})); ie{h} = cell(1,length(m{h})); hi{h} = cell(1,length(m{h})); for i = 1:length(m{h}) mi = m{h}{i}; fi = f{h}{i}; pfi = pf{h}{i}{1}; he{h}{i} = zeros(1,size(mi,2),size(mi,3)); ie{h}{i} = zeros(1,size(mi,2),size(mi,3)); hi{h}{i} = zeros(1,size(mi,2),size(mi,3)); for j = 1:size(mi,3) for k = 1:size(mi,2) mk = mi(:,k,j); fk = fi(:,k,j); pfk = sort(pfi(:,k)); z = zeros(2,length(pfk)); for l = 1:length(pfk) if isnan(pfk(l)) continue end f1 = find(diff(mk(pfk(l):-1:1)) >= 0,1); f2 = find(diff(mk(pfk(l):end)) >= 0,1); z(1,l) = pfk(l) - f1 + 1; z(2,l) = pfk(l) + f2 - 1; end z(:,~z(1,:)) = []; hark = 0; inhk = sum(mk(1:z(1)-1).^2); for l = 1:size(z)-1 hark = hark + sum(mk(z(1,l):z(2,l)).^2); inhk = inhk + sum(mk(z(2,l)+1:z(1,l+1)-1).^2); end inhk = inhk + sum(mk(z(end)+1:end).^2); he{h}{i}(1,k,j) = hark; ie{h}{i}(1,k,j) = inhk; hi{h}{i}(1,k,j) = hark / (hark + inhk); end end end end he = mirscalar(s,'Data',he,'Title','Harmonic Energy'); ie = mirscalar(s,'Data',ie,'Title','Inharmonic Energy'); hi = mirscalar(s,'Data',hi,'Title','Harmonicity'); h = {hi he ie p};
github
martinarielhartmann/mirtooloct-master
mirread2014.m
.m
mirtooloct-master/MIRToolbox/mirread2014.m
5,612
utf_8
0834239f85502c1063d7246164c71cd0
function [d,tp,fp,f,l,b,n,ch] = mirread2014(extract,orig,load,folder,verbose) % Read the audio file ORIG, at temporal position indicated by EXTRACT. If % EXTRACT is empty, all the audio file is loaded. % If LOAD is set to 0, just the meta-data is collected, and the actual % audio data is not taken into consideration. If it is set to 1, the % data are loaded from the current directory. If LOAD is a string, it % is considered as the path of the directory. % If FOLDER is set to 1, no error is returned if an audio file cannot be % loaded. % Output: % D is the audio signal, % TP are the temporal positions, % FP are the two extreme temporal positions (used for frame positions), % F is the sampling rate, % L is the duration in seconds, % B is the resolution in number of bits, % N is the file name. % CH are the channel index. if nargin < 5 verbose = 0; end d = {}; f = {}; l = {}; b = {}; tp = {}; fp = {}; n = {}; ch = {}; if strcmp(orig,'.') || strcmp(orig,'..') return end try [d,f,l,b,tp,fp,n,ch] = audioreader(extract,@audioread,orig,load,verbose,folder); catch if folder return end warning('Did you specify the file extension? This will be required in future versions of Matlab.'); warning('off','MATLAB:audiovideo:wavread:functionToBeRemoved'); warning('off','MATLAB:audiovideo:auread:functionToBeRemoved'); try [d,f,l,b,tp,fp,n,ch] = audioreader(extract,@wavread,orig,load,verbose,folder); catch err.wav = lasterr; try [d,f,l,b,tp,fp,n,ch] = audioreader(extract,@auread,orig,load,verbose,folder); catch err.au = lasterr; try [d,f,l,b,tp,fp,n,ch] = audioreader(extract,@mp3read,orig,load,verbose,folder); catch err.mp3 = lasterr; try [d,f,l,b,tp,fp,n,ch] = audioreader(extract,@aiffread,orig,load,verbose,folder); catch err.aiff = lasterr; if length(orig)>4 && strcmpi(orig(end-3:end),'.bdf') try [d,f,l,b,tp,fp,n,ch] = audioreader(extract,@bdfread,orig,load,verbose,folder); catch if not(strcmp(err.wav(1:11),'Error using') && folder) misread(orig, err); end end else if not(strcmp(err.wav(1:11),'Error using') && folder) misread(orig, err); end end end end end end end function [d,f,l,b,tp,fp,n,ch] = audioreader(extract,reader,file,load,verbose,folder) n = file; if folder file = ['./',file]; end if load if isempty(extract) if isequal(reader,@audioread) [s,f] = audioread(file); i = audioinfo(file); if isfield(i,'BitsPerSample') b = i.BitsPerSample; elseif isfield(i,'BitRate') b = i.BitRate; else b = NaN; end else [s,f,b] = reader(file); end else if isequal(reader,@audioread) i = audioinfo(file); f = i.SampleRate; if isfield(i,'BitsPerSample') b = i.BitsPerSample; elseif isfield(i,'BitRate') b = i.BitRate; else b = NaN; end s = audioread(file,extract(1:2)); else [unused,f,b] = reader(file,1); s = reader(file,extract(1:2)); end if length(extract) > 2 s = s(:,extract(3)); end end if verbose disp([file,' loaded.']); end d{1} = reshape(s,size(s,1),1,size(s,2)); %channels along dim 3 ch = 1:size(s,2); if isempty(extract) tp{1} = (0:size(s,1)-1)'/f; else tp{1} = (extract(1)-1+(0:size(s,1)-1))'/f; end l{1} = (size(s,1)-1)/f; if isempty(s) fp{1} = 0; else fp{1} = tp{1}([1 end]); end else if isequal(reader,@audioread) i = audioinfo(file); d = i.TotalSamples; f = i.SampleRate; if isfield(i,'BitsPerSample') b = i.BitsPerSample; elseif isfield(i,'BitRate') b = i.BitRate; else b = NaN; end ch = i.NumChannels; else if isequal(reader,@mp3read) [dsize,f,b] = reader(file,'size'); else [unused,f,b] = reader(file,1); dsize = reader(file,'size'); end d = dsize(1); ch = dsize(2); end l = d/f; tp = {}; fp = {}; end function [y,fs,nbits] = bdfread(file,check) DAT = openbdf(file); NRec = DAT.Head.NRec; if not(length(check)==2) b = readbdf(DAT,1); y = length(b.Record(43,:)) * NRec; else y = []; if mirwaitbar handle = waitbar(0,'Loading BDF channel...'); else handle = 0; end for i = 1:NRec b = readbdf(DAT,i); y = [y;b.Record(43,:)']; if handle waitbar(i/NRec,handle); end end if handle delete(handle) end end fs = DAT.Head.SampleRate(43); nbits = NaN; function misread(file,err) display('Here are the error message returned by each reader:'); display(err.wav); display(err.au); display(err.mp3); display(err.aiff); mirerror('MIRREAD',['Cannot open file ',file]);
github
martinarielhartmann/mirtooloct-master
pluscell.m
.m
mirtooloct-master/MIRToolbox/pluscell.m
271
utf_8
4b18198163a886e445d0b3b1f88a2f50
function varargout = pluscell(x,varargin) specif.combinechunk = 'Average'; varargout = mirfunction(@pluscell,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = mirtype(a{1}); function y = main(x,option,postoption) y = plus(x{1},x{2});
github
martinarielhartmann/mirtooloct-master
mirmedian.m
.m
mirtooloct-master/MIRToolbox/mirmedian.m
2,776
utf_8
28428cd9fc147e21412168f1a226c8c1
function varargout = mirmedian(f,varargin) % m = mirmedian(f) returns the median along frames of the feature f % % f can be a structure array composed of features. In this case, % m will be structured the same way. if isa(f,'mirstruct') data = get(f,'Data'); for fi = 1:length(data) data{fi} = mirmedian(data{fi}); end varargout = {set(f,'Data',data)}; elseif isstruct(f) fields = fieldnames(f); for i = 1:length(fields) field = fields{i}; stat.(field) = mirmedian(f.(field)); end varargout = {stat}; else specif.nochunk = 1; varargout = mirfunction(@mirmedian,f,varargin,nargout,specif,@init,@main); end function [x type] = init(x,option) type = ''; function m = main(f,option,postoption) if iscell(f) f = f{1}; end if isa(f,'mirhisto') warning('WARNING IN MIRmedian: histograms are not taken into consideration yet.') m = struct; return end fp = get(f,'FramePos'); ti = get(f,'Title'); if 0 %get(f,'Peaks') if not(isempty(get(f,'PeakPrecisePos'))) stat = addstat(struct,get(f,'PeakPrecisePos'),fp,'PeakPos'); stat = addstat(stat,get(f,'PeakPreciseVal'),fp,'PeakMag'); else stat = addstat(struct,get(f,'PeakPosUnit'),fp,'PeakPos'); stat = addstat(stat,get(f,'PeakVal'),fp,'PeakMag'); end else d = get(f,'Data'); end l = length(d); m = cell(1,l); for i = 1:l dd = d{i}; if iscell(dd) m{i} = cell(1,length(dd)); fpi = cell(1,length(dd)); for j = 1:length(dd) ddj = dd{j}; if iscell(ddj) ddj = uncell(ddj); end for k = 1:size(ddj,1) ddk = ddj(k,:); ddk(isnan(ddk)) = []; m{i}{j}(k,1) = median(ddk,2); end fpi{j} = [fp{i}{j}(1);fp{i}{j}(end)]; end fp{i} = fpi; elseif size(dd,2) < 2 nonan = find(not(isnan(dd))); dn = dd(nonan); m{i}{1} = median(dn,2); else %diffp = fp{i}{1}(1,2:end) - fp{i}{1}(1,1:end-1); %if round((diffp(2:end)-diffp(1:end-1))*1000) % Not regular sampling (in mirattacktime for instance) % framesampling = NaN; %else % framesampling = fp{i}{1}(1,2)-fp{i}{1}(1,1); %end dd = median(dd,4); m{i} = {NaN(size(dd,1),1,size(dd,3))}; for k = 1:size(dd,1) for l = 1:size(dd,3) dk = dd(k,:,l); nonan = find(not(isnan(dk))); if not(isempty(nonan)) dn = dk(nonan); m{i}{1}(k,1,l) = median(dn,2); end end end end end m = mirscalar(f,'Data',m,'Title',['Median of ',ti],'FramePos',fp);
github
martinarielhartmann/mirtooloct-master
mtimescell.m
.m
mirtooloct-master/MIRToolbox/mtimescell.m
277
utf_8
77d174f26c270bf0a8697dec0f49668e
function varargout = mtimescell(x,varargin) specif.combinechunk = 'Average'; varargout = mirfunction(@mtimescell,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = mirtype(x{1}); function y = main(x,option,postoption) y = mtimes(x{1},x{2});
github
martinarielhartmann/mirtooloct-master
maxcell.m
.m
mirtooloct-master/MIRToolbox/maxcell.m
268
utf_8
95ea81e59ab86695378063af0e68208a
function varargout = maxcell(x,varargin) specif.combinechunk = 'Average'; varargout = mirfunction(@maxcell,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = mirtype(a{1}); function y = main(x,option,postoption) y = max(x{1},x{2});
github
martinarielhartmann/mirtooloct-master
mirbeatspectrum.m
.m
mirtooloct-master/MIRToolbox/mirbeatspectrum.m
2,388
utf_8
64687e175e19c6e8b154c4fe557e190c
function varargout = mirbeatspectrum(orig,varargin) % n = mirbeatspectrum(m) evaluates the beat spectrum. % [n,m] = mirbeatspectrum(m) also return the similarity matrix on which % the estimation is made. % Optional argument: % mirbeatspectrum(...,s) specifies the estimation method. % Possible values: % s = 'Diag', summing simply along the diagonals of the matrix. % s = 'Autocor', based on the autocorrelation of the matrix. % mirbeatspectrum(...,'Distance',f) specifies the name of a dissimilarity % distance function, from those proposed in the Statistics Toolbox % (help pdist). % default value: f = 'cosine' % J. Foote, M. Cooper, U. Nam, "Audio Retrieval by Rhythmic Similarity", % ISMIR 2002. dist.key = 'Distance'; dist.type = 'String'; dist.default = 'cosine'; option.dist = dist; meth.type = 'String'; meth.choice = {'Diag','Autocor'}; meth.default = 'Autocor'; option.meth = meth; specif.option = option; varargout = mirfunction(@mirbeatspectrum,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirscalar')) if isamir(x,'miraudio') x = mirmfcc(x,'frame',.025,'s',.01,'s','Rank',8:30); end x = mirsimatrix(x,'Distance',option.dist,'Similarity'); end type = 'mirscalar'; function y = main(orig,option,postoption) if iscell(orig) orig = orig{1}; end fp = get(orig,'FramePos'); if not(isa(orig,'mirscalar')) s = get(orig,'Data'); total = cell(1,length(s)); for k = 1:length(s) for h = 1:length(s{k}) maxfp = find(fp{k}{h}(2,:)>4,1); if isempty(maxfp) maxfp = Inf; else fp{k}{h}(:,maxfp+1:end) = []; end l = min(length(s{k}{h}),maxfp); total{k}{h} = zeros(1,l); if strcmpi(option.meth,'Diag') for i = 1:l total{k}{h}(i) = mean(diag(s{k}{h},i-1)); end else for i = 1:l total{k}{h}(i) = mean(mean(s{k}{h}(:,1:l-i+1).*s{k}{h}(:,i:l))); end end end end else total = get(orig,'Data'); end n = mirscalar(orig,'Data',total,'FramePos',fp,'Title','Beat Spectrum'); y = {n orig};
github
martinarielhartmann/mirtooloct-master
mirsegment.m
.m
mirtooloct-master/MIRToolbox/mirsegment.m
19,232
utf_8
1f3a212fffc5cc7346fe3f2283271b8c
function [f,p,m,fe] = mirsegment(x,varargin) % f = mirsegment(a) segments an audio signal. It can also be the name of an % audio file or 'Folder', for the analysis of the audio files in the % current folder. The segmentation of audio signal already decomposed % into frames is not available for the moment. % f = mirsegment(...,'Novelty') segments using a self-similarity matrix % (Foote & Cooper, 2003) (by default) % f = mirsegment(...,feature) bases the segmentation strategy on a % specific feature. % 'Spectrum': from FFT spectrum (by default) % 'MFCC': from MFCCs % 'Keystrength': from the key strength profile % 'AutocorPitch': from the autocorrelation function computed as % for pitch extraction. % The option related to this feature extraction can be specified. % Example: mirsegment(...,'Spectrum','Window','bartlett') % mirsegment(...,'MFCC','Rank',1:10) % mirsegment(...,'Keystrength','Weight',.5) % These feature need to be frame-based, in order to appreciate their % temporal evolution. Therefore, the audio signal x is first % decomposed into frames. This decomposition can be controled % using the 'Frame' keyword. % The options available for the chosen strategies can be specified % directly as options of the segment function. % Example: mirsegment(a,'Novelty','KernelSize',10) % f = mirsegment(...,'HCDF') segments using the Harmonic Change Detection % Function (Harte & Sandler, 2006) % f = mirsegment(...,'RMS') segments at positions of long silences. A % frame decomposed RMS is computed using mirrms (with default % options), and segments are selected from temporal positions % where the RMS rises to a given 'On' threshold, until temporal % positions where the RMS drops back to a given 'Off' threshold. % f = mirsegment(...,'Off',t1) specifies the RMS 'Off' threshold. % Default value: t1 = .01 % f = mirsegment(...,'On',t2) specifies the RMS 'On' threshold. % Default value: t2 = .02 % % f = mirsegment(a,s) segments a using the results of a segmentation % analysis s. s can be for instance: % - the peaks detected on an analysis of the audio % - the results of mirpeaks('Segment'). % % f = mirsegment(a,v) where v is an array of numbers, segments a using % the temporal positions specified in v (in s.) % % Foote, J. & Cooper, M. (2003). Media Segmentation using Self-Similarity % Decomposition,. In Proc. SPIE Storage and Retrieval for Multimedia % Databases, Vol. 5021, pp. 167-75. % Harte, C. A. & Sandler, M. B. (2006). Detecting harmonic change in % musical audio, in Proceedings of Audio and Music Computing for % Multimedia Workshop, Santa Barbara, CA. % [f,p] = mirsegment(...) also displays the analysis produced by the chosen % strategy. % For 'Novelty', p is the novelty curve. % For 'HCDF', p is the Harmonic Change Detection Function. % [f,p,m] = mirsegment(...) also displays the preliminary analysis % undertaken in the chosen strategy. % For 'Novelty', m is the similarity matrix. % For 'HCDF', m is the tonal centroid. % [f,p,m,fe] = mirsegment(...) also displays the temporal evolution of the % feature used for the analysis. % f = mirsegment(...,'Novelty') mfc.key = {'Rank','MFCC'}; mfc.type = 'Integers'; mfc.default = 0; mfc.keydefault = 1:13; option.mfc = mfc; K.key = 'KernelSize'; K.type = 'Integer'; K.default = 128; option.K = K; distance.key = 'Distance'; distance.type = 'String'; distance.default = 'cosine'; option.distance = distance; measure.key = {'Measure','Similarity'}; measure.type = 'String'; measure.default = 'exponential'; option.measure = measure; tot.key = 'Total'; tot.type = 'Integer'; tot.default = Inf; option.tot = tot; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = .1; option.cthr = cthr; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [3 .1]; option.frame = frame; ana.type = 'String'; ana.choice = {'Spectrum','Keystrength','AutocorPitch','Pitch'}; ana.default = 0; option.ana = ana; % f = mirsegment(...,'Spectrum') band.choice = {'Mel','Bark','Freq'}; band.type = 'String'; band.default = 'Freq'; option.band = band; mi.key = 'Min'; mi.type = 'Integer'; mi.default = 0; option.mi = mi; ma.key = 'Max'; ma.type = 'Integer'; ma.default = 0; option.ma = ma; norm.key = 'Normal'; norm.type = 'Boolean'; norm.default = 0; option.norm = norm; win.key = 'Window'; win.type = 'String'; win.default = 'hamming'; option.win = win; % f = mirsegment(...,'Silence') throff.key = 'Off'; throff.type = 'Integer'; throff.default = .01; option.throff = throff; thron.key = 'On'; thron.type = 'Integer'; thron.default = .02; option.thron = thron; strat.choice = {'Novelty','HCDF','RMS','Silence'}; % should remain as last field strat.default = 'Novelty'; strat.position = 2; option.strat = strat; specif.option = option; p = {}; m = {}; fe = {}; if isempty(x) f = {}; return end if isa(x,'mirdesign') if not(get(x,'Eval')) % During bottom-up construction of the general design [unused option] = miroptions(@mirframe,x,specif,varargin); type = get(x,'Type'); f = mirdesign(@mirsegment,x,option,{},struct,type); sg = get(x,'Segment'); if not(isempty(sg)) f = set(f,'Segment',sg); else f = set(f,'Segment',option.strat); end else % During top-down evaluation initiation f = evaleach(x); if iscell(f) f = f{1}; end p = x; end elseif isa(x,'mirdata') [unused option] = miroptions(@mirframe,x,specif,varargin); if ischar(option.strat) dx = get(x,'Data'); if strcmpi(option.strat,'Novelty') if not(option.frame.length.val) if strcmpi(option.ana,'Keystrength') option.frame.length.val = .5; option.frame.hop.val = .2; elseif strcmpi(option.ana,'AutocorPitch') ... || strcmpi(option.ana,'Pitch') option.frame.length.val = .05; option.frame.hop.val = .01; else option.frame.length.val = .05; option.frame.hop.val = 1; end end fr = mirframenow(x,option); if not(isequal(option.mfc,0)) fe = mirmfcc(fr,'Rank',option.mfc); elseif strcmpi(option.ana,'Spectrum') fe = mirspectrum(fr,'Min',option.mi,'Max',option.ma,... 'Normal',option.norm,option.band,... 'Window',option.win); elseif strcmpi(option.ana,'Keystrength') fe = mirkeystrength(fr); elseif strcmpi(option.ana,'AutocorPitch') ... || strcmpi(option.ana,'Pitch') [unused,fe] = mirpitch(x,'Frame'); else fe = fr; end [n m] = mirnovelty(fe,'Distance',option.distance,... 'Measure',option.measure,... 'KernelSize',option.K); p = mirpeaks(n,'Total',option.tot,... 'Contrast',option.cthr,... 'Chrono','NoBegin','NoEnd'); elseif strcmpi(option.strat,'HCDF') if not(option.frame.length.val) option.frame.length.val = .743; option.frame.hop.val = 1/8; end fr = mirframenow(x,option); %[df m fe] = mirhcdf(fr); df = mirhcdf(fr); p = mirpeaks(df); elseif strcmpi(option.strat,'RMS') if not(option.frame.length.val) option.frame.length.val = .05; option.frame.hop.val = .5; end fr = mirframenow(x,option); df = mirrms(fr); fp = get(df,'FramePos'); p = mircompute(@findsilenceRMS,df,fp,option.throff,option.thron); elseif strcmpi(option.strat,'Silence') o = mironsets(x,'Normal','AcrossSegments'); t = get(o,'Pos'); p = mircompute(@findsilenceenvelope,o,t,3,.3,2); end f = mirsegment(x,p); else dx = get(x,'Data'); dt = get(x,'Time'); de = []; if isa(option.strat,'mirpitch') ds = get(option.strat,'Start'); de = get(option.strat,'End'); fp = get(option.strat,'FramePos'); elseif isa(option.strat,'mirscalar') ds = get(option.strat,'PeakPos'); fp = get(option.strat,'FramePos'); elseif isa(option.strat,'mirdata') ds = get(option.strat,'AttackPos'); if isempty(ds) || isempty(ds{1}) ds = get(option.strat,'PeakPos'); end xx = get(option.strat,'Pos'); else ds = option.strat; fp = cell(1,length(dx)); end st = cell(1,length(dx)); sx = cell(1,length(dx)); cl = cell(1,length(dx)); l = cell(1,length(dx)); for k = 1:length(dx) dxk = dx{k}; % values in kth audio file dtk = dt{k}; % time positions in kth audio file dek = []; if isa(option.strat,'mirdata') dsk = ds{k}{1}; % segmentation times in kth audio file if ~isempty(de) dek = de{k}{1}; end elseif iscell(ds) dsk = ds{k}; elseif size(ds,2) == length(dx) dsk = {ds(:,k)}; else dsk = ds; end if length(dxk) == 1 fsk = []; % the structured array of segmentation times % is flatten else fsk = cell(1,length(dxk)); end for j = 1:length(dsk) dej = []; if iscell(dsk) %isa(option.strat,'mirdata') dsj = dsk{j}; % segmentation times in jth segment if ~isempty(dek) dej = dek{j}; end else dsj = dsk; end if not(iscell(dsj)) dsj = {dsj}; if ~isempty(dek) dej = {dej}; end end for m = 1:length(dsj) % segmentation times in mth bank channel if isa(option.strat,'mirscalar') dsm = fp{k}{m}(1,dsj{m}); if ~isempty(dej) dem = fp{k}{m}(2,dej{m}); end elseif isa(option.strat,'mirdata') dsm = xx{k}{m}(dsj{m}); else dsm = dsj{m}; end if iscell(dsm) dsm = dsm{1}; if iscell(dsm) dsm = dsm{1}; end end if size(dsm,1)>1 && size(dsm,2)>1 mirerror('MIRSEGMENT',... 'Segmentation matrix is not of required size.'); end dsm(dsm <= dtk{j}(1)) = []; dsm(dsm >= dtk{j}(end)) = []; if ~isempty(dek) dem(dem <= dtk{j}(1)) = []; dem(dem >= dtk{j}(end)) = []; end % It is presupposed here that the segmentations times % for a given channel are not decomposed per frames, % because the segmentation of the frame decomposition % is something that does not seem very clear. % Practically, the peak picking for instance is based % therefore on a frame analysis (such as novelty), and % segmentation are inferred between these frames... if length(dxk) == 1 fsk = [fsk dsm]; end end if length(dxk)>1 fsk{j} = sort(dsm); end end if length(dxk) == 1 fsk = sort(fsk); % Here is the chronological ordering end if isempty(fsk) ffsk = {[dtk{1}(1);dtk{end}(end)]}; sxk = {dxk{1}}; stk = {dtk{1}}; lk = {dtk{end}(end)-dtk{1}(1)}; n = 1; fpsk = ffsk; elseif ~isempty(de) ffsk = cell(1,length(fsk)); for h = 1:length(fsk) ffsk{h} = [fsk(h);dem(h)]; end n = length(ffsk); crd = zeros(2,n); % the sample positions of the % segmentations in the channel for i = 1:n crd(1,i) = find(dtk{1} >= ffsk{i}(1),1); crd(2,i) = find(dtk{1} >= ffsk{i}(2),1); end sxk = cell(1,n); % each cell contains a segment stk = cell(1,n); % each cell contains % the corresponding time positions lk = cell(1,n); % each cell containing the segment length for i = 1:n sxk{i} = dxk{1}(crd(1,i):crd(2,i),1,:); stk{i} = dtk{1}(crd(1,i):crd(2,i)); lk{i} = size(stk{i},1); end fpsk = ffsk; elseif length(dxk) == 1 % Input audio is not already segmented ffsk = cell(1,length(fsk)+1); ffsk{1} = [dtk{1}(1);fsk(1)]; for h = 1:length(fsk)-1 ffsk{h+1} = [fsk(h);fsk(h+1)]; end ffsk{end} = [fsk(end);dtk{end}(end)]; n = length(ffsk); crd = zeros(1,n+1); % the sample positions of the % segmentations in the channel crd0 = 0; for i = 1:n crd0 = crd0 + find(dtk{1}(crd0+1:end)>=ffsk{i}(1),1); crd(i) = crd0; end crd(n+1) = size(dxk{1},1)+1; sxk = cell(1,n); % each cell contains a segment stk = cell(1,n); % each cell contains % the corresponding time positions lk = cell(1,n); % each cell containing the segment length for i = 1:n sxk{i} = dxk{1}(crd(i):crd(i+1)-1,1,:); stk{i} = dtk{1}(crd(i):crd(i+1)-1); lk{i} = size(stk{i},1); end fpsk = ffsk; else sxk = {}; stk = {}; fpsk = {}; lk = {}; n = 0; for i = 1:length(dxk) if isempty(fsk{i}) fpsk{end+1} = [dtk{i}(1);dtk{i}(end)]; sxk{end+1} = dxk{i}; stk{end+1} = dtk{i}; lk{end+1} = dtk{i}(end)-dtk{i}(1); n = n+1; else ffsk = cell(1,length(fsk{i})+1); ffsk{1} = [dtk{i}(1);fsk{i}(1)]; for h = 1:length(fsk{i})-1 ffsk{h+1} = [fsk{i}(h);fsk{i}(h+1)]; end ffsk{end} = [fsk{i}(end);dtk{i}(end)]; ni = length(ffsk); crd = zeros(1,ni+1); % the sample positions of the % segmentations in the channel crd0 = 0; for j = 1:ni crd0 = crd0 + find(dtk{i}(crd0+1:end)>=ffsk{j}(1),1); crd(j) = crd0; end crd(ni+1) = size(dxk{i},1)+1; for j = 1:ni sxk{end+1} = dxk{i}(crd(j):crd(j+1)-1,1,:); stk{end+1} = dtk{i}(crd(j):crd(j+1)-1); lk{end+1} = size(stk{end},1); fpsk{end+1} = ffsk{j}; end n = n+ni; end end end sx{k} = sxk; st{k} = stk; fp{k} = fpsk; l{k} = lk; cl{k} = 1:n; end f = set(x,'Data',sx,'Time',st,'FramePos',fp,... 'Length',l,'Clusters',cl); p = strat; m = {}; fe = {}; end else [f p] = mirsegment(miraudio(x),varargin{:}); end function p = findsilenceRMS(d,fp,throff,thron) d = [0 d 0]; begseg = find(d(1:end-1)<thron & d(2:end)>=thron); nseg = length(begseg); endseg = zeros(1,nseg); removed = []; for i = 1:nseg endseg(i) = begseg(i) + find(d(begseg(i)+1:end)<=throff, 1)-1; if i>1 && endseg(i) == endseg(i-1) removed = [removed i]; end end begseg(removed) = []; %endseg(removed) = []; %endseg(end) = min(endseg(end),length(d)+1); p = fp(1,begseg); %; fp(2,endseg-1)]; function p = findsilenceenvelope(d,t,l,thr1,thr2) high = 0; p = []; i = 1; while i <= length(d) if d(i) > high high = d(i); elseif d(i) < high*thr1 && i <= length(d)-l pi = find(d(i+1:end) > high*thr1,1); if isempty(pi) break end low = min(d(i:i+pi)); if high-low < .02 break end i = i+pi; if pi < l break end pi = find(d(i:end) > low*thr2,1); if isempty(pi) break end i = i+pi-1; p(end+1) = t(i); high = d(i); end i = i+1; end
github
martinarielhartmann/mirtooloct-master
mircentroid.m
.m
mirtooloct-master/MIRToolbox/mircentroid.m
3,220
utf_8
a86a35685785ce380a1e68dc10219b92
function varargout = mircentroid(x,varargin) % c = mircentroid(x) calculates the centroid (or center of gravity) of x. % x can be either: % - a spectrum (spectral centroid), % - an envelope (temporal centroid) % - a histogram, % - or any data. Only the positive ordinates of the data are taken % into consideration. % c = mircentroid(x,'Peaks') calculates the centroid of the peaks only. % Beauchamp 1982 version? peaks.key = 'Peaks'; peaks.type = 'String'; peaks.choice = {0,'NoInterpol','Interpol'}; peaks.default = 0; peaks.keydefault = 'NoInterpol'; option.peaks = peaks; minrms.key = 'MinRMS'; % Should we change this? minrms.when = 'After'; minrms.type = 'Numerical'; minrms.default = .005; option.minrms = minrms; maxentropy.key = 'MaxEntropy'; maxentropy.when = 'After'; maxentropy.type = 'Numerical'; maxentropy.default = .95; option.maxentropy = maxentropy; specif.option = option; varargout = mirfunction(@mircentroid,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirdata')) || isamir(x,'miraudio') x = mirspectrum(x); end type = 'mirscalar'; function c = main(x,option,postoption) if iscell(x) x = x{1}; end if option.peaks if strcmpi(option.peaks,'Interpol') pt = get(x,'PeakPrecisePos'); pv = get(x,'PeakPreciseVal'); else pt = get(x,'PeakPos'); pv = get(x,'PeakVal'); end cx = cell(1,length(pt)); for h = 1:length(pt) cx{h} = cell(1,length(pt{h})); for i = 1:length(pt{h}) pti = pt{h}{i}; pvi = pv{h}{i}; %if isempty(pti) nfr = size(pti,2); nbd = size(pti,3); ci = zeros(1,nfr,nbd); for j = 1:nfr for k = 1:nbd ptk = pti{1,j,k}; pvk = pvi{1,j,k}; sk = sum(pvk); ci(1,j,k) = sum(ptk.*pvk) ./ sk; end end cx{h}{i} = ci; end end else cx = peaksegments(@centroid,get(x,'Data'),get(x,'Pos')); end if isa(x,'mirspectrum') t = 'Spectral centroid'; elseif isa(x,'mirenvelope') t = 'Temporal centroid'; else t = ['centroid of ',get(x,'Title')]; end c = mirscalar(x,'Data',cx,'Title',t); if isstruct(postoption) c = after(x,c,postoption.minrms,postoption.maxentropy); end function c = centroid(d,p) c = (p'*d) ./ sum(d); function c = after(x,c,minrms,maxentropy) v = get(c,'Data'); if minrms && strcmpi(get(x,'Title'),'Spectrum') r = mirrms(x,'Warning',0); v = mircompute(@trimrms,v,get(r,'Data'),minrms); end if maxentropy && maxentropy < 1 h = mirentropy(x,'MinRMS',minrms); v = mircompute(@trimentropy,v,get(h,'Data'),maxentropy); end c = set(c,'Data',v); function d = trimrms(d,r,minrms) r = r/max(max(r)); pos = find(r<minrms); for i = 1:length(pos) d{pos(i)} = NaN; % Adding warning messages? end d = {d}; function d = trimentropy(d,r,minentropy) pos = find(r>minentropy); for i = 1:length(pos) d{pos(i)} = NaN; end d = {d};
github
martinarielhartmann/mirtooloct-master
mirbrightness.m
.m
mirtooloct-master/MIRToolbox/mirbrightness.m
2,411
utf_8
e606c2a0139812150d9ca8ad065f1149
function varargout = mirbrightness(x,varargin) % b = mirbrightness(s) calculates the spectral brightness, i.e. the amount % of spectral energy corresponding to frequencies higher than a given % cut-off threshold. % Optional arguments: % b = mirbrightness(s,'CutOff',f) specifies the frequency cut-off % threshold in Hz. % Default value: f = 1500 Hz. % % Typical values for the frequency cut-off threshold: % 3000 Hz in Juslin 2000, p. 1802. % 1000 Hz and 500 Hz in Laukka, Juslin and Bresin 2005. % % Juslin, P. N. (2000). Cue utilization in communication of emotion in % music performance: relating performance to perception. Journal of % Experimental Psychology: Human Perception and Performance, 26(6), 1797?813. % Laukka, P., Juslin, P. N., and Bresin, R. (2005). A dimensional approach % to vocal expression of emotion. Cognition and Emotion, 19, 633?653. cutoff.key = 'CutOff'; cutoff.type = 'Integer'; cutoff.default = 1500; option.cutoff = cutoff; minrms.key = 'MinRMS'; minrms.when = 'After'; minrms.type = 'Numerical'; minrms.default = .005; option.minrms = minrms; specif.option = option; specif.defaultframelength = .05; specif.defaultframehop = .5; varargout = mirfunction(@mirbrightness,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirspectrum')) x = mirspectrum(x); end type = 'mirscalar'; function b = main(s,option,postoption) if iscell(s) s = s{1}; end m = get(s,'Magnitude'); f = get(s,'Frequency'); w = warning('query','MATLAB:divideByZero'); warning('off','MATLAB:divideByZero'); v = mircompute(@algo,m,f,option.cutoff); warning(w.state,'MATLAB:divideByZero'); b = mirscalar(s,'Data',v,'Title','Brightness'); if isstruct(postoption) b = after(s,b,postoption.minrms); end function v = algo(m,f,k) if not(any(max(f)>k)) warning('WARNING in MIRBRIGHTNESS: Frequency range of the spectrum too low for the estimation of brightness.'); end sm = sum(m); v = sum(m(f(:,1,1) > k,:,:)) ./ sm; function b = after(s,b,minrms) v = get(b,'Data'); if minrms r = mirrms(s,'Warning',0); v = mircompute(@trimrms,v,get(r,'Data'),minrms); end b = set(b,'Data',v); function d = trimrms(d,r,minrms) r = r/max(max(r)); pos = find(r<minrms); for i = 1:length(pos) d(pos(i)) = NaN; end d = {d};
github
martinarielhartmann/mirtooloct-master
nthoutput.m
.m
mirtooloct-master/MIRToolbox/nthoutput.m
440
utf_8
319f756e43e6a02e1cf1c3868c4da5be
function varargout = nthoutput(orig,varargin) nth.type = 'Integer'; nth.default = 1; nth.position = 2; option.nth = nth; specif.option = option; varargout = mirfunction(@nthoutput,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = mirtype(x); if iscell(type) type = type{option.nth}; end function y = main(x,option,postoption) y = x{option.nth}; %y = x{1}{option.nth};
github
martinarielhartmann/mirtooloct-master
mirmap.m
.m
mirtooloct-master/MIRToolbox/mirmap.m
9,257
utf_8
e2f934119eadec0f16f594bc8b212468
function res = mirmap(predics_ref,ratings_ref,dist,alpha,delta) % mirmap(predictors_file, ratings_file) performs a statistical mapping % between ratings associated to a set of audio recordings, and a set of % variables computed for the same set of audio recordings. It might be % useful in particular when the set of predictors is large and diverse. if nargin<3 dist = 'lse'; end if nargin<4 alpha = 1; end if nargin<5 delta = .00001; end crosscor_thres = .6; dist = str2func(dist); try predics = import(predics_ref); catch err mirerror('MIRMAP',['Cannot load properly the predictors file ' ... prefics_ref '. Check MIRtoolbox User''s Manual']); end try ratings = import(ratings_ref); catch err display(err.message) mirerror('MIRMAP',['Cannot load properly the ratings file ' ... ratings_ref '. Check MIRtoolbox User''s Manual']); end predics = normalize(predics,dist,alpha,delta,'predictions',predics_ref); if isempty(predics.data) res = []; return end ratings = normalize(ratings,dist,alpha,delta,'ratings',ratings_ref); res = map(predics,ratings,crosscor_thres); %% function output = import(ref) output.data = []; output.fields = {}; output.normal = []; if not(iscell(ref)) ref = {ref}; end for i = 1:length(ref) if not(iscell(ref{i})) ref{i} = {ref{i}}; end if ischar(ref{i}{1}) for j = 1:length(ref{i}) importj = importdata(ref{i}{j}); if not(isstruct(importj)) imp = importj; importj = struct; importj.data = imp; for k = 1:size(imp,2) importj.textdata{k} = [ref{i}{j},'_',num2str(k)]; end end if j == 1 import = importj; else [c ia ib] = intersect(import.textdata(1,2:end),... importj.textdata(1,2:end)); import.textdata = [import.textdata(:,[1 ia+1]);... importj.textdata(2:end,[1 ib+1])]; import.data = [import.data(:,ia);importj.data(:,[1 ib+1])]; end end output.data = [output.data import.data]; nbfields = size(import.data,2); field = import.textdata(1,:); field = field(end-nbfields+1 : end); output.fields = [output.fields field]; else output.data = [output.data ref{i}{1}]; for j = 1:size(ref{i},2) output.fields = [output.fields num2str(j)]; end end end ndata = size(output.data,2); output.normal = NaN(1,ndata); warning('off','stats:lillietest:OutOfRangeP'); for i = 1:ndata data = output.data(:,i); data = data(~isnan(data)); if length(data) < 4 output.normal(i) = 0; else output.normal(i) = ~lillietest(data); end end %% function res = map(predics,ratings,crosscor_thres) nbrates = size(ratings.data,2); nbpreds = size(predics.data,2); res.normal.cor = NaN(nbpreds,nbrates); res.normal.pval = NaN(nbpreds,nbrates); res.significant = cell(nbrates,1); for j = 1:nbrates figure set(gca,'YDir','reverse') hold on select = []; % list of selected features for i = 1:nbpreds if ~predics.normal(i) res.normal.cor(i,j) = NaN; continue end [R P] = corrcoef(predics.data(:,i),ratings.data(:,j),... 'rows','pairwise'); res.normal.pval(i,j) = P(2); if P(2)<.05 % statistically significant select(end+1) = i; % included into the list of selected features res.normal.cor(i,j) = R(2); else res.normal.cor(i,j) = NaN; end end %res.inter(:,:,j) = corrcoef(predics.data,'rows','pairwise'); [unused index] = sort(abs(res.normal.cor(select,j)),'descend'); index = select(index); res.significant{j}.cor = res.normal.cor(index,j); res.significant{j}.pval = res.normal.pval(index,j); res.significant{j}.inter = corrcoef(predics.data(:,index),'rows','pairwise'); %res.inter(index,index,j); res.significant{j}.fields = {predics.fields{index}}; res.significant{j}.alpha = predics.alpha(index); res.significant{j}.lambda = predics.lambda(index); k = 0; corfields = {}; corbest = []; for i = 1:length(select) inter = max(abs(res.significant{j}.inter(1:i-1,i))); if i == 1 || inter < crosscor_thres % Features sufficiently independent to the better scoring ones % are selected k = k+1; if i == 1 own = 1; else own = 1-inter; end col = res.significant{j}.pval(i); x1 = min(0,res.significant{j}.cor(i)); y1 = k-own/2; x2 = x1+abs(res.significant{j}.cor(i)); y2 = k+own/2; pcolor([x1 x1;x2 x2],[y1 y2;y1 y2],[col col;col col]) corbest = [corbest i]; corfields = [corfields res.significant{j}.fields{i}]; i res.significant{j}.fields{i} res.significant{j}.cor(i) inter end end set(gca,'YTick',1:k,'YTickLabel',corfields)%,... % 'Position',[.4 .11 .5 .815]) colorbar grid on title(['Correlation with rating ',ratings.fields{j}]) predata = standardize(predics.data(:,index(corbest))); %% to be put out of the loop res.best{j}.index = corbest; res.best{j}.fields = {res.significant{j}.fields{corbest}}; res.best{j}.alpha = res.significant{j}.alpha(corbest); res.best{j}.lambda = res.significant{j}.lambda(corbest); if isempty(select) close elseif length(corbest)>1 display('****************************************') display(['Regression for rating ',ratings.fields{j}]) ratej = standardize(ratings.data(:,j)); stepwisefit(predata,ratej,'maxiter',10); [b,se,pval,inmodel,stats,nextstep,history] ... = stepwisefit(predata,ratej,'maxiter',10,'scale','on'); res.best{j}.fields{find(inmodel)} %stepwise(predata,ratej,[]);%,.001,.001); pause end end function x = standardize(x) %mx = mean(x); %x = x-repmat(mx,[size(x,1) 1]); %sx = std(x); %sx(sx==0) = 1; %x = x./repmat(sx,[size(x,1) 1]); %% function output = normalize(input,dist,alpha,delta,txt,filename) fields = input.fields; nbfields = length(fields); output = input; h = waitbar(0,['Normalizing ',txt]); for i = 1:nbfields waitbar((i-1)/nbfields,h,['Normalizing ',txt,fields{i}]); d = input.data(:,i); if length(d(~isnan(d)))>3 && ~input.normal(i) %figure(1) %hist(d,round(7.5*log(size(d,1)))); %figure(2) %normplot(d) [output.data(:,i) output.alpha(i) output.lambda(i)] = ... boxcox_search(d,dist,alpha,delta); %figure(3) %hist(output.data(:,i),round(7.5*log(size(d,1)))); output.normal(i) = ~lillietest(output.data(:,i),.01); %figure(4) %normplot(data(:,i)) end end display('Excluded:') output.fields{~output.normal} display('..') output.data(:,~output.normal) = []; output.fields(~output.normal) = []; output.normal(~output.normal) = []; if max(~output.normal) output.alpha(~output.normal) = []; output.lambda(~output.normal) = []; end %if strcmpi(filename(end-3:end),'.txt') % filename = filename(1:end-4); %end %filename = [filename '.mir.txt']; %mirexport(filename,output); close(h); function [y resalpha lambda] = boxcox_search(x,dist,alpha,delta) if nargin<2 dist = @lse; end if nargin<3 alpha = 0; end lambda = -10:.01:10; if min(x)<0 x = x-min(x); resalpha = -min(x); else resalpha = 0; end y = boxcox_transf(x,lambda); [y lambda d] = optimize(y,lambda,dist,x); %y = y(~isnan(y)); while lillietest(y,.01) && alpha > delta yp = boxcox_transf(x+alpha,lambda); %plot(alpha,lse(yp,lambda,x)) if dist(yp,lambda,x)<d x = x+alpha; resalpha = resalpha + alpha; y = yp; alpha = alpha*.999; d = dist(y,lambda,x); else minalpha = min(alpha,min(x)); % to avoid negative values yn = boxcox_transf(x - minalpha,lambda); %plot(alpha,lse(yn,lambda,x)) if dist(yn,lambda,x)<d x = minalpha; resalpha = resalpha - minalpha; y = yn; alpha = alpha*.999; d = dist(y,lambda,x); else alpha = alpha/2; end end end %plot(lambda,dist(y,lambda,x),'.r') function y = boxcox_transf(x,lambda) lambda0 = find(~lambda); if min(x)<0 x = x-min(x); end x = repmat(x,[1 length(lambda)]); lambda = repmat(lambda,[size(x,1) 1]); y = (x.^lambda-1)./lambda; y(:,lambda0) = log(x(:,lambda0)); function [z,lambda,d] = optimize(y,lambda,dist,x) [d index] = min(dist(y,lambda,x)); lambda = lambda(index); z = y(:,index); function d = lse(y,lambda,x) d = skewness(y).^2 + (kurtosis(y)-3).^2/4; % equation used in Jarque-Bera test %plot(lambda,d,'.') function d = mle(y,lambda,x) d = -size(y,1)/2*log(var(y))+(lambda-1)*sum(log(x));
github
martinarielhartmann/mirtooloct-master
mirsum.m
.m
mirtooloct-master/MIRToolbox/mirsum.m
5,221
utf_8
c32347b96fc7dde3df06fc81737c6298
function varargout = mirsum(orig,varargin) % s = mirsum(f) sums the channels together % % Optional arguments: % mirsum(f,'Centered') centers the resulting envelope. % mirsum(f,'Mean') divides the summation by the number of channels. % mirsum(f,'Weights')... c.key = 'Centered'; c.type = 'Boolean'; c.default = 0; c.when = 'After'; option.c = c; m.key = 'Mean'; m.type = 'Boolean'; m.default = 0; m.when = 'After'; option.m = m; adj.key = 'Adjacent'; adj.type = 'Integer'; adj.default = 1; option.adj = adj; weights.key = 'Weights'; weights.type = 'Integer'; weights.default = []; option.weights = weights; specif.option = option; if isamir(orig,'mirtemporal') specif.eachchunk = @eachtemporalchunk; specif.combinechunk = 'Concat'; %@combinetemporalchunk; else specif.combinechunk = @combinechunk; end varargout = mirfunction(@mirsum,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = mirtype(x); function s = main(x,option,postoption) x = purgedata(x); if iscell(x) x = x{1}; end d = get(x,'Data'); pp = get(x,'PeakPos'); pv = get(x,'PeakVal'); pm = get(x,'PeakMode'); p = get(x,'Pos'); sc = cell(1,length(d)); spp = cell(1,length(d)); spv = cell(1,length(d)); spm = cell(1,length(d)); for h = 1:length(d) dh = d{h}; sch = cell(1,length(dh)); spph = cell(1,length(dh)); spvh = cell(1,length(dh)); spmh = cell(1,length(dh)); for i = 1:length(dh) % Summation of signal s3 = size(dh{i},3); if not(isempty(option.weights)) weights = reshape(option.weights,1,1,length(option.weights)); if length(weights)~=s3 %warning('WARNING in MIRSUM..'); weights = weights(1,1,1:s3); end dh{i} = dh{i}.*repmat(weights,[size(dh{i},1),size(dh{i},2),1]); end if option.adj < 2 sch{i} = sum(dh{i},3); else m0 = option.adj; nc1 = size(dh{i},3); nc2 = ceil(nc1/m0); sch{i} = zeros(size(dh{i},1),size(dh{i},2),nc2); for j = 1:nc2 sch{i}(:,:,j) = sum(dh{i}(:,:,(j-1)*m0+1:min(j*m0,nc1))... ,3); end end % Summation of peaks if not(isempty(pp)) && not(isempty(pp{1})) ppi = pp{h}{i}; pvi = pv{h}{i}; pmi = pm{h}{i}; nfr = size(ppi,2); nbd = size(ppi,3); sppi = cell(1,nfr,1); spvi = cell(1,nfr,1); spmi = cell(1,nfr,1); for j = 1:nfr sppj = []; spvj = []; spmj = []; for k = 1:nbd ppk = ppi{1,j,k}; pvk = pvi{1,j,k}; pmk = pmi{1,j,k}; for l = 1:length(ppk) fp = find(ppk(l) == sppj); if fp spvj(fp) = spvj(fp) + pvk(l); else sppj(end+1) = ppk(l); spvj(end+1) = pvk(l); spmj(end+1) = pmk(l); end end end sppi{1,j,1} = sppj; spvi{1,j,1} = spvj; spmi{1,j,1} = spmj; end spph{i} = sppi; spvh{i} = spvi; spmh{i} = spmi; else spph{i} = []; spvh{i} = []; spmh{i} = []; end if not(isempty(p)) && not(isempty(p{h})) p{h}{i} = p{h}{i}(:,:,1); end end sc{h} = sch; spp{h} = spph; spv{h} = spvh; spm{h} = spmh; end s = set(x,'Data',sc,'Pos',p,'PeakPos',spp,'PeakVal',spv,'PeakMode',spm); if not(isempty(postoption)) s = post(s,postoption); end function s = post(s,option) if option.c d = get(s,'Data'); for k = 1:length(d) for i = 1:length(d{k}) d{k}{i} = center_(d{k}{i}); end end s = set(s,'Data',d); end if option.m d = get(s,'Data'); ch = get(s,'Channels'); if not(isempty(ch)) for k = 1:length(d) for i = 1:length(d{k}) d{k}{i} = d{k}{i}/length(ch{k}); end ch{k} = [1]; end s = set(s,'Data',d,'Channels',ch); end end function [y orig] = eachtemporalchunk(orig,option,missing) [y orig] = mirsum(orig,option); %function y = combinetemporalchunk(old,new) %do = get(old,'Data'); %to = get(old,'Time'); %dn = get(new,'Data'); %tn = get(new,'Time'); %y = set(old,'Data',{{[do{1}{1};dn{1}{1}]}},... % 'Time',{{[to{1}{1};tn{1}{1}]}}); % function y = combinechunk(old,new) if isa(old,'mirspectrum') warning('WARNING IN MIRSUM: not yet fully generalized to mirspectrum') end doo = get(old,'Data'); doo = doo{1}{1}; dn = get(new,'Data'); dn = dn{1}{1}; if length(dn) < length(doo) dn(length(doo),:,:) = 0; % Zero-padding end y = set(old,'ChunkData',doo+dn);
github
martinarielhartmann/mirtooloct-master
mironsets.m
.m
mirtooloct-master/MIRToolbox/mironsets.m
33,222
utf_8
5f4967930b6c3ac6998051ef4af37132
function varargout = mironsets(x,varargin) % o = mironsets(x) shows a temporal curve where peaks relate to the % position of note onset times, and estimates those note onset % positions. % Optional arguments: % mironsets(...,f) selects the strategy for the computation of the % onset detection function. % f = 'Envelope': Envelope of the audio signal. (Default choice). % With two methods for envelope extraction: % mironsets(...,'Spectro') (Default): % mironsets(...,'SpectroFrame',fl,fh) species the frame % length fl (in s.) and the hop factor fh (as a value % between 0 and 1) % Default values: fl = .1 s., fh = .1 % the frequency reassigment method can be specified: % 'Freq' (default), 'Mel', 'Bark' or 'Cents' (cf. mirspectrum). % mironsets(...,'Filter'): % mironsets(...,'Filterbank',nc) specifies a preliminary % filterbank decomposition into nc channels. If nc = 0, % no decomposition is performed. % Default value: 40. % mironsets(...,'FilterbankType',ft) specifies the type of % filterbank (see mirfilterbank). % Default value: 'Gammatone'; % Options associated to the mirenvelope function can be % passed here as well (see help mirenvelope): % 'FilterType','Tau','PreDecim' % mironsets(...,'Sum','no') does not sum back the channels at % the end of the computation. The resulting onset curve % remains therefore decomposed into several channels. % Options associated to the mirenvelope function can be % passed here as well (see help mirenvelope): % 'HalfwaveCenter','Diff','HalfwaveDiff','Center', % 'Smooth', 'Sampling','Log','Power','Lambda', % ,'PostDecim','UpSample' % f = 'SpectralFlux': Spectral flux of the audio signal. % Options associated to the mirflux function can be % passed here as well (see help mirflux): % 'Inc' (toggled on by default here), % 'Halfwave' (toggled on by default here), % 'Complex' (toggled off by default), % 'Median' (toggled on by default here) % f = 'Emerge': is an improved version of the 'SpectralFlux' % method that is able to detect more notes and in the same % time ignore the spectral variation produced by vibrato. %%%% % When the 'Emerge' method is used for academic research, please cite the % following publication: % Lartillot, O., Cereghetti, D., Eliard, K., Trost, W. J., Rappaz, M.-A., % Grandjean, D., "Estimating tempo and metrical features by tracking % the whole metrical hierarchy", 3rd International Conference on % Music & Emotion, Jyv?skyl?, 2013. %%%% % f = 'Pitch ':computes a frame-decomposed autocorrelation function , % of same default characteristics than those returned % by mirpitch, with however a range of frequencies set by % the following options: % 'Min' (set by default to 30 Hz), % 'Max' (set by default to 1000 Hz), % and subsequently computes the novelty curve of the % resulting similatrix matrix. % Option associated to the mirnovelty function can be % passed here as well (see help mirnovelty): % 'KernelSize' (set by default to 32 samples) % mironsets(...,'Detect',d) toggles on or off the onset detection, % which is based on the onset detection function. % (By default toggled on.) % Option associated to the mirpeaks function can be specified as % well: % 'Contrast' with default value c = .01 % 'Threshold' with default value t = 0 % 'Single' detects only the highest peak. % mironsets(...,'Attack') (or 'Attacks') detects attack phases. % mironsets(...,'Release') (or 'Releases') detects release phases. % mironsets(...,'Frame',...) decomposes into frames, with default frame % length 3 seconds and hop factor .1 % Preselected onset detection models: % mironsets(...,'Scheirer') corresponds to (Scheirer, 1998): % mironsets(...,'FilterBankType','Scheirer',... % 'FilterType','HalfHann','Sampling',200,... % 'HalfWaveDiff','Sum',0,'Detect',0) % mironsets(...,'Klapuri99') corresponds to most of (Klapuri, 1999). %% options related to 'Envelope': env.key = 'Envelope'; env.type = 'Boolean'; env.default = NaN; option.env = env; envmethod.key = 'Method'; % optional envmethod.type = 'Boolean'; option.envmethod = envmethod; envmeth.type = 'String'; envmeth.choice = {'Filter','Spectro'}; envmeth.default = 'Spectro'; option.envmeth = envmeth; %% options related to 'Filter': filter.key = 'FilterType'; filter.type = 'String'; filter.choice = {'IIR','HalfHann','Butter'}; filter.default = 'IIR'; option.filter = filter; tau.key = 'Tau'; tau.type = 'Integer'; tau.default = .02; option.tau = tau; fb.key = {'Filterbank','NbChannels'}; fb.type = 'Integer'; fb.default = 40; option.fb = fb; filtertype.key = 'FilterbankType'; filtertype.type = 'String'; %filtertype.choice = {'Gammatone','2Channels','Scheirer','Klapuri'}; filtertype.default = 'Gammatone'; option.filtertype = filtertype; decim.key = {'Decim','PreDecim'}; decim.type = 'Integer'; decim.default = 0; option.decim = decim; hilb.key = {'Hilbert'}; hilb.type = 'Boolean'; hilb.default = 0; option.hilb = hilb; %% options related to 'Spectro': band.type = 'String'; band.choice = {'Freq','Mel','Bark','Cents'}; band.default = 'Freq'; option.band = band; specframe.key = 'SpectroFrame'; specframe.type = 'Integer'; specframe.number = 2; specframe.default = [.1 .1]; option.specframe = specframe; powerspectrum.key = 'PowerSpectrum'; powerspectrum.type = 'Boolean'; powerspectrum.default = 1; option.powerspectrum = powerspectrum; timesmooth.key = 'TimeSmooth'; timesmooth.type = 'Boolean'; timesmooth.default = 0; timesmooth.keydefault = 10; option.timesmooth = timesmooth; terhardt.key = 'Terhardt'; terhardt.type = 'Boolean'; terhardt.default = 0; option.terhardt = terhardt; sum.key = 'Sum'; sum.type = 'Boolean'; sum.default = 1; option.sum = sum; chwr.key = 'HalfwaveCenter'; chwr.type = 'Boolean'; chwr.default = 0; chwr.when = 'After'; option.chwr = chwr; mu.key = 'Mu'; mu.type = 'Integer'; mu.default = 0; mu.keydefault = 100; option.mu = mu; oplog.key = 'Log'; oplog.type = 'Boolean'; oplog.default = 0; oplog.when = 'After'; option.log = oplog; minlog.key = 'MinLog'; minlog.type = 'Integer'; minlog.default = 0; minlog.when = 'After'; option.minlog = minlog; oppow.key = 'Power'; oppow.type = 'Boolean'; oppow.default = 0; oppow.when = 'After'; option.power = oppow; diffenv.key = 'DiffEnvelope'; % obsolete, replaced by 'Diff' diffenv.type = 'Boolean'; diffenv.default = 0; option.diffenv = diffenv; diff.key = 'Diff'; diff.type = 'Integer'; diff.default = 0; diff.keydefault = 1; diff.when = 'After'; option.diff = diff; diffhwr.key = 'HalfwaveDiff'; diffhwr.type = 'Integer'; diffhwr.default = 0; diffhwr.keydefault = 1; diffhwr.when = 'After'; option.diffhwr = diffhwr; lambda.key = 'Lambda'; lambda.type = 'Integer'; lambda.default = 1; lambda.when = 'After'; option.lambda = lambda; c.key = 'Center'; c.type = 'Boolean'; c.default = 0; c.when = 'After'; option.c = c; aver.key = 'Smooth'; aver.type = 'Integer'; aver.default = 0; aver.keydefault = 30; aver.when = 'After'; option.aver = aver; ds.key = {'Down','PostDecim'}; ds.type = 'Integer'; if isamir(x,'mirenvelope') ds.default = 1; else ds.default = NaN; end ds.when = 'After'; ds.chunkcombine = 'During'; option.ds = ds; sampling.key = 'Sampling'; sampling.type = 'Integer'; sampling.default = 0; sampling.when = 'After'; option.sampling = sampling; up.key = {'UpSample'}; up.type = 'Integer'; up.default = 0; up.keydefault = 2; option.up = up; normal.key = 'Normal'; normal.type = 'String'; normal.choice = {0,1,'AcrossSegments'}; normal.default = 1; normal.when = 'After'; option.normal = normal; %% options related to 'SpectralFlux' flux.key = 'SpectralFlux'; flux.type = 'Boolean'; flux.default = 0; option.flux = flux; complex.key = 'Complex'; complex.type = 'Boolean'; complex.when = 'Both'; complex.default = 0; option.complex = complex; inc.key = 'Inc'; inc.type = 'Boolean'; inc.default = 1; option.inc = inc; median.key = 'Median'; median.type = 'Integer'; median.number = 2; median.default = [.2 1.3]; median.when = 'After'; option.median = median; hw.key = 'Halfwave'; hw.type = 'Boolean'; hw.default = 1; hw.when = 'After'; option.hw = hw; %% options related to 'Pitch': pitch.key = 'Pitch'; pitch.type = 'Boolean'; pitch.default = 0; option.pitch = pitch; min.key = 'Min'; min.type = 'Integer'; min.default = 30; option.min = min; max.key = 'Max'; max.type = 'Integer'; max.default = 1000; option.max = max; novelty.key = 'Novelty'; novelty.type = 'Boolean'; novelty.default = 0; option.novelty = novelty; kernelsize.key = 'KernelSize'; kernelsize.type = 'Integer'; kernelsize.default = 0; option.kernelsize = kernelsize; %% options related to 'Emerge': sgate.key = {'SmoothGate','Emerge'}; sgate.type = 'String'; sgate.choice = {'Goto','Lartillot'}; sgate.default = ''; sgate.keydefault = 'Lartillot'; sgate.when = 'Both'; option.sgate = sgate; minres.key = 'MinRes'; minres.type = 'Integer'; minres.default = 10; option.minres = minres; %% nomodif.key = 'NoModif'; nomodif.type = 'Boolean'; nomodif.default = 0; option.nomodif = nomodif; %% options related to event detection detect.key = 'Detect'; detect.type = 'String'; detect.choice = {'Peaks','Valleys',0,'no','off'}; detect.default = 'Peaks'; detect.keydefault = 'Peaks'; detect.when = 'After'; option.detect = detect; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = NaN; cthr.when = 'After'; option.cthr = cthr; thr.key = 'Threshold'; thr.type = 'Integer'; thr.default = 0; thr.when = 'After'; option.thr = thr; single.key = 'Single'; single.type = 'Boolean'; single.default = 0; single.when = 'After'; option.single = single; attack.key = {'Attack','Attacks'}; attack.type = 'Boolean'; attack.default = 0; attack.when = 'After'; option.attack = attack; release.key = {'Release','Releases'}; release.type = 'String'; release.choice = {'Olivier','Valeri',0,'no','off'}; release.default = 0; release.keydefault = 'Olivier'; release.when = 'After'; option.release = release; %% preselection presel.choice = {'Scheirer','Klapuri99'}; presel.type = 'String'; presel.default = 0; option.presel = presel; %% 'Frame' option frame.key = 'Frame'; frame.type = 'Integer'; frame.when = 'After'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [3 .1]; option.frame = frame; specif.option = option; specif.eachchunk = 'Normal'; specif.combinechunk = 'Concat'; specif.extensive = 1; specif.title = 'Onset curve'; %used for miroptions varargout = mirfunction(@mironsets,x,varargin,nargout,specif,@init,@main); %% INIT function [y type] = init(x,option) if iscell(x) x = x{1}; end if option.nomodif y = x; return end if ischar(option.presel) if strcmpi(option.presel,'Scheirer') option.filtertype = 'Scheirer'; option.filter = 'HalfHann'; option.envmeth = 'Filter'; elseif strcmpi(option.presel,'Klapuri99') option.filtertype = 'Klapuri'; option.filter = 'HalfHann'; option.envmeth = 'Filter'; option.decim = 180; option.mu = 100; end end if option.diffenv option.env = 1; end if isnan(option.env) if option.flux || option.pitch || option.novelty || ... ~isempty(option.sgate) option.env = 0; else option.env = 1; end end if ~option.kernelsize if option.pitch option.kernelsize = 32; elseif option.novelty option.kernelsize = 64; end end if isamir(x,'miraudio') y = []; if option.env if strcmpi(option.envmeth,'Filter') && option.fb>1 fb = mirfilterbank(x,option.filtertype,'NbChannels',option.fb); else fb = x; end y = mirenvelope(fb,option.envmeth,option.band,... 'Frame',option.specframe(1),option.specframe(2),... 'FilterType',option.filter,... 'Hilbert',option.hilb,... 'Tau',option.tau,'UpSample',option.up,... 'PreDecim',option.decim,'PostDecim',0,... 'Mu',option.mu,... 'PowerSpectrum',option.powerspectrum,... 'TimeSmooth',option.timesmooth,... 'Terhardt',option.terhardt); end if option.flux z = mirflux(x,'Inc',option.inc,'Complex',option.complex); %,'Dist','City'); %%%%%%%%%%%%%%%%%??? if isempty(y) y = z; else y = y+z; end end if option.pitch [unused ac] = mirpitch(x,'Frame','Min',option.min,'Max',option.max); z = mirnovelty(ac,'KernelSize',option.kernelsize); if isempty(y) y = z; else y = y+z; end elseif option.novelty s = mirspectrum(x,'max',1000,'Frame',.05,.2,'MinRes',3,'dB'); %c = mircepstrum(x,'Frame',.05,.2); %[p ac] = mirpitch(x,'Frame'); z = mirnovelty(s,'KernelSize',option.kernelsize,... 'Flux',... ...'Distance','Euclidean',... 'Similarity','oneminus'); if isempty(y) y = z; else y = y+z; end elseif ~isempty(option.sgate) if strcmpi(option.sgate,'Goto') x = miraudio(x,'Sampling',22050); y = mirspectrum(x,'Frame',.04644,.25); else y = mirspectrum(x,'Frame',.05,.2,.... 'MinRes',option.minres,'dB','max',5000); if option.minres < 1 && isa(y,'mirdesign') y = set(y,'ChunkSizeFactor',get(x,'ChunkSizeFactor')*5); %20/option.minres); end end y = mirflux(y,'Inc','BackSmooth',option.sgate,'Dist','Gate'); %% other ideas %y = mircepstrum(x,'min',50,'Hz','max',600,'Hz','Frame',.05,.2); %y = mirnovelty(y);%,'Width',1000); %y = mirsimatrix(y,'Width',1000); %'Distance','NewGate' %y = mirpeaks(y,'Contrast',.1,'Threshold',.3); %y = mirautocor(x,'Freq','max',5000,'Hz','Frame',.05,.2); end elseif (option.pitch && not(isamir(x,'mirscalar'))) ... || isamir(x,'mirsimatrix') y = mirnovelty(x,'KernelSize',option.kernelsize); elseif isamir(x,'mirscalar') || isamir(x,'mirenvelope') || ... (isamir(x,'mirspectrum') && ~isempty(option.sgate)) y = x; else y = mirflux(x,'Inc',option.inc,'Complex',option.complex); %Not used... end type = 'mirenvelope'; %% MAIN function o = main(o,option,postoption) if not(isempty(option)) && ischar(option.presel) if strcmpi(option.presel,'Scheirer') postoption.sampling = 200; postoption.diffhwr = 1; option.sum = 0; postoption.detect = 0; elseif strcmpi(option.presel,'Klapuri99') postoption.diffhwr = 1; option.sum = 0; postoption.ds = 0; o2 = o; end end if iscell(o) o = o{1}; end if not(isempty(option)) && option.diffenv postoption.diff = 1; end if isa(o,'mirenvelope') if isfield(postoption,'sampling') && postoption.sampling o = mirenvelope(o,'Sampling',postoption.sampling); elseif isfield(postoption,'ds') if isnan(postoption.ds) if option.decim || strcmpi(option.envmeth,'Spectro') postoption.ds = 0; else postoption.ds = 16; end end if postoption.ds o = mirenvelope(o,'Down',postoption.ds); end end end if isfield(postoption,'cthr') if isa(o,'mirenvelope') if postoption.power o = mirenvelope(o,'Power'); end if postoption.diff o = mirenvelope(o,'Diff',postoption.diff,... 'Lambda',postoption.lambda,... 'Complex',postoption.complex); end if postoption.diffhwr o = mirenvelope(o,'HalfwaveDiff',postoption.diffhwr,... 'Lambda',postoption.lambda,... 'Complex',postoption.complex); end if postoption.aver o = mirenvelope(o,'Smooth',postoption.aver); end if postoption.chwr o = mirenvelope(o,'HalfwaveCenter'); end elseif isa(o,'mirscalar') && strcmp(get(o,'Title'),'Spectral flux') && ... isempty(postoption.sgate) if postoption.median o = mirflux(o,'Median',postoption.median(1),postoption.median(2),... 'Halfwave',postoption.hw); else o = mirflux(o,'Halfwave',postoption.hw); end elseif isa(o,'mirscalar') && strcmp(get(o,'Title'),'Novelty') if postoption.diff o = mirenvelope(o,'Diff',postoption.diff,... 'Lambda',postoption.lambda,... 'Complex',postoption.complex); end end end if isa(o,'mirspectrum') [tmp o] = gettmp(o); d = get(o,'Data'); [doo tmp] = mircompute(@newonset,d,tmp); o = mirscalar(o,'Data',doo,'Title','Onset curve'); o = settmp(o,tmp); %elseif isa(o,'mircepstrum') % pp = get(o,'PeakPosUnit'); % pv = get(o,'PeakVal'); % do = mircompute(@cepstronset,pp,pv); % o = mirscalar(o,'Data',do,'Title','Onset curve'); end if isfield(option,'sum') && option.sum o = mirsum(o,'Adjacent',option.sum); end if isa(o,'mirenvelope') && isfield(postoption,'normal') && ... ~isequal(postoption.normal,0) && ~get(o,'Log') o = mirenvelope(o,'Normal',postoption.normal); end if isa(o,'mirenvelope') && isfield(postoption,'log') && postoption.log o = mirenvelope(o,'Log'); end if isfield(option,'presel') && ... ischar(option.presel) && strcmpi(option.presel,'Klapuri99') % o, already computed, corresponds to mirenvelope(o,'Mu','HalfwaveDiff'); % o is the relative distance function W in (Klapuri, 99); o2 = mirenvelope(o2,'HalfwaveDiff'); % o2 is the absolute distance function D in (Klapuri, 99); p = mirpeaks(o,'Contrast',.2,'Chrono'); p2 = mirpeaks(o2,'ScanForward',p,'Chrono'); o = combinepeaks(p,p2,.05); clear o2 p p2 filtfreq = 44*[2.^ ([ 0:2, ( 9+(0:17) )/3 ]) ];% Center frequencies of bands o = mirsum(o,'Weights',(filtfreq(1:end-1)+filtfreq(2:end))/2); o = mirenvelope(o,'Smooth',12); end if isfield(postoption,'detect') if postoption.c || ~isempty(postoption.sgate) o = mirenvelope(o,'Center'); end if isa(o,'mirenvelope') && postoption.minlog o = mirenvelope(o,'MinLog',postoption.minlog); end end o = mirframenow(o,postoption); if isfield(postoption,'detect') && ischar(postoption.detect) if isnan(postoption.cthr) || not(postoption.cthr) if ischar(postoption.detect) || postoption.detect postoption.cthr = .01; end elseif postoption.cthr if not(ischar(postoption.detect) || postoption.detect) postoption.detect = 'Peaks'; end end if postoption.single total = 1; noend = 0; else total = Inf; noend = 1; end if strcmpi(postoption.detect,'Peaks') o = mirpeaks(o,'Total',total,'SelectFirst',0,... 'Threshold',postoption.thr,'Contrast',postoption.cthr,... 'Order','Abscissa','NoBegin','NoEnd',noend); elseif strcmpi(postoption.detect,'Valleys') o = mirpeaks(o,'Total',total,'SelectFirst',0,... 'Threshold',postoption.thr,'Contrast',postoption.cthr,... 'Valleys','Order','Abscissa','NoBegin','NoEnd',noend); end nop = cell(size(get(o,'Data'))); o = set(o,'AttackPos',nop,'ReleasePos',nop); end if (isfield(postoption,'attack') && not(isequal(postoption.attack,0))) || ... (isfield(postoption,'release') && not(isequal(postoption.release,0))) pp = get(o,'PeakPos'); pv = get(o,'PeakVal'); pm = get(o,'PeakMode'); ppp = get(o,'PeakPrecisePos'); ppv = get(o,'PeakPreciseVal'); d = get(o,'Data'); if postoption.attack v = mirpeaks(o,'Total',Inf,'SelectFirst',0,... 'Contrast',postoption.cthr,... 'Valleys','Order','Abscissa','NoEnd'); st = get(v,'PeakPos'); [st pp] = mircompute(@startattack,d,pp,st); %[st pp pv pm ppp ppv] = mircompute(@startattack,d,pp,pv,pm,ppp,ppv); else st = {{{}}}; end if ischar(postoption.release) && ~strcmpi(postoption.release,'No') ... && ~strcmpi(postoption.release,'Off') v = mirpeaks(o,'Total',Inf,'SelectFirst',0,... 'Contrast',postoption.cthr,'Threshold',.7,... 'Valleys','Order','Abscissa','NoBegin'); rl = get(v,'PeakPos'); rl = mircompute(@endrelease,d,pp,rl); %[rl pp pv pm ppp ppv st] = mircompute(@endrelease,d,pp,pv,pm,ppp,ppv,st,postoption.release); o = set(o,'ReleasePos',rl); end o = set(o,'AttackPos',st,'PeakPos',pp,'PeakVal',pv,'PeakMode',pm,... 'PeakPrecisePos',ppp,'PeakPreciseVal',ppv); end title = get(o,'Title'); if not(length(title)>11 && strcmp(title(1:11),'Onset curve')) o = set(o,'Title',['Onset curve (',title,')']); end function [doo tmp] = newonset(d,tmp) d = d - max(max(max(d))); doo = zeros(1,size(d,2)); if isempty(tmp) activ = []; inactiv = []; old = []; else activ = tmp.activ; inactiv = tmp.inactiv; old = tmp.old; end for i = 1:size(d,2) dd = diff(d(:,i)); new = find(dd(1:end-1) > 0 & dd(2:end) < 0) + 1; oldnew = [new d(new,i)]; if ~isempty(old) maj = find(d(new,i) > -20); while ~isempty(maj) [min_o best_o] = min(abs(old(:,1) - new(maj(1)))); min_a = Inf; for k = 1:length(activ) da = abs(activ(k).idx(end) - new(maj(1))); if da < min_a min_a = da; best_a = k; end end if min_a == min_o activ(best_a).idx(end+1) = new(maj(1)); activ(best_a).mag(end+1) = d(new(maj(1)),i); activ(best_a).tim(end+1) = i; if length(activ(best_a).idx) < 10 doo(i) = doo(i) + d(new(maj(1)),i) + 20; end elseif old(best_o,2) < -20 found = 0; for k = 1:length(inactiv) if inactiv(k).idx(end) == old(best_o,1) activ(end+1) = inactiv(k); inactiv(k) = []; activ(end).idx(end+1) = new(maj(1)); activ(end).mag(end+1) = d(new(maj(1)),i); activ(end).tim(end+1) = i; if length(activ(end).idx) < 10 doo(i) = doo(i) + d(new(maj(1)),i) + 20; end found = 1; break end end if ~found activ(end+1).idx = new(maj(1)); activ(end).mag = d(new(maj(1)),i); activ(end).tim = i; doo(i) = doo(i) + d(new(maj(1)),i) + 20; end end new(maj(1)) = []; maj(1) = []; maj = maj - 1; end j = 1; while j <= length(inactiv) if isempty(new) inactiv(j:end) = []; break end [unused best_i] = min(abs(new - inactiv(j).idx(end))); if unused < 100 inactiv(j).idx(end+1) = new(best_i); inactiv(j).mag(end+1) = d(new(best_i)); inactiv(j).tim(end+1) = i; j = j+1; else inactiv(j) = []; end new(best_i) = []; end j = 1; while j <= length(activ) if activ(j).tim(end) < i if isempty(new) activ(j) = []; continue end if isempty(inactiv) inactiv = activ(j); else inactiv(end+1) = activ(j); end activ(j) = []; [unused best_i] = min(abs(new - inactiv(end).idx(end))); inactiv(end).idx(end+1) = new(best_i); inactiv(end).mag(end+1) = d(new(best_i)); inactiv(end).tim(end+1) = i; new(best_i) = []; else j = j+1; end end end old = oldnew; end tmp.activ = activ; tmp.inactiv = inactiv; tmp.old = old; function doo = oldnewonset(d) tc = 10; dy = 2; doo = NaN(1,size(d,2)); for i = 1:size(d,2) doo(i) = 0; for j = dy+1:size(d,1)-dy ddj = d(j,i) - max(max(d(j+(-dy:+dy),i-1:-1:max(i-tc,1)))); if ddj > 0 doo(i) = doo(i) + ddj; end end end doo function [st pp] = startattack(d,pp,st) %pv,pm,ppp,ppv) pp = sort(pp{1}); if isempty(pp) st = {{} {}}; return end st = st{1}; if ~isempty(st) && st(1)>pp(1) dd = diff(d,1,1); % d' p = find(dd((pp(1)-1)-1:-1:1)<=0,1); if isempty(p) st0 = 1; else st0 = ((pp(1)-1)-p)+1; end st = [st0 st]; end if length(st)>length(pp) st = st(1:length(pp)); else pp = pp(1:length(st)); end %thres = .015; for i = 1:length(st) dd = diff(d(st(i):pp(i))); [mad mdd] = max(dd); f2 = find(dd(mdd+1:end)<mad/5,1); if ~isempty(f2) pp(i) = st(i) + mdd + f2 - 1; end f1 = find(dd(mdd-1:-1:1)<mad/5,1); if ~isempty(f1) st(i) = st(i) + mdd - f1; end %sti = find(dd > max(dd)/3,1); %ppi = find(dd(end:-1:1) > max(dd)/3,1); %st(i) = st(i) + sti - 1; %pp(i) = pp(i) - ppi + 1; end st = {{st} {pp}}; return %% pv = pv{1}; pm = pm{1}; ppp = ppp{1}; ppv = ppv{1}; st = zeros(size(pp)); i = 1; dd = diff(d,1,1); % d' ddd = diff(dd,1,1); % d'' dddd = diff(ddd,1,1); % d''' while i<=length(pp) % Start attack is identified to previous valley in d. p = find(dd((pp(i)-1)-1:-1:1)<0,1); if isempty(p) st(i) = 1; else st(i) = ((pp(i)-1)-p)+1; if i>1 && st(i-1)==st(i) if d(pp(i))>d(pp(i-1)) del = i-1; else del = i; end st(del) = []; pp(del) = []; pv(del) = []; pm(del) = []; ppp(del) = []; ppv(del) = []; i = i-1; end end % Start attack is identified to previous peak in d''. %p = find(dddd((pp(i)-1)-1:-1:1)<0,1); % previous decreasing d'' %if isempty(p) % st(i) = 1; %else % n = find(dddd((pp(i)-1)-p-1:-1:1)>0,1); % previous increasing d'' % if isempty(n) % st(i) = 1; % else % st(i) = ((pp(i)-1)-p-(n-1))+1; % end % if i>1 && st(i-1)==st(i) % if d(pp(i))>d(pp(i-1)) % del = i-1; % else % del = i; % end % st(del) = []; % pp(del) = []; % pv(del) = []; % pm(del) = []; % ppp(del) = []; % ppv(del) = []; % i = i-1; % end %end i = i+1; end st = {{st} {pp} {pv} {pm} {ppp} {ppv}}; function [rt pp] = endrelease(d,pp,rt) %pv,pm,ppp,ppv,rt,meth) pp = sort(pp{1}); if isempty(pp) rt = {{} {}}; return end rt = rt{1}; if ~isempty(rt) && rt(end)<pp(end) dd = diff(d,1,1); % d' p = find(dd((pp(end)+1)-1:end)>=0,1); if isempty(p) rte = length(d); else rte = ((pp(end)+1)+p)+1; end rt = [rt rte]; end %thres = .015; for i = 1:length(rt) dd = diff(d(rt(i):-1:pp(i))); [mad mdd] = max(dd); ed = find(dd(mdd+1:end)<mad/5,1); if ~isempty(ed) pp(i) = rt(i) - mdd - ed - 1; end pp(i + find(pp(i+1:end) <= rt(i))) = []; end rt = {{[pp;rt]}}; return %% pv = pv{1}; pm = pm{1}; ppp = ppp{1}; ppv = ppv{1}; if not(isempty(st)) st = st{1}; end rt = zeros(size(pp)); i = 1; dd = diff(d,1,1); % d' ddd = diff(dd,1,1); % d'' dddd = diff(ddd,1,1); % d''' while i<=length(pp) if strcmpi(meth,'Olivier') % Release attack is identified to next (sufficiently positive) peak % in d''. l = find(ddd((pp(i)-1):end)<min(ddd)/100,1); % next d'' sufficiently negative if isempty(l) rt(i) = length(d); else p = find(ddd((pp(i)-1)+(l-1)+1:end)>max(ddd)/100,1); % next increasing d'' if isempty(p) rt(i) = length(d); else n = find(dddd((pp(i)-1)+(l-1)+p+1:end)<0,1); % next decreasing d'' if isempty(n) rt(i) = length(d); else rt(i) = ((pp(i)-1)+(l-1)+p+n)+1; end end end elseif strcmpi(meth,'Valeri') p = find(dd((pp(i)-1)+1:end)>min(dd)/100,1); % find point nearest to min(dd)/100 from current peak. if isempty(p) rt(i) = length(d); elseif p<=3 %that means if p is less than 3 points away from the peak then it can not be considered as the end point of release. %Assumption is that the whole DSR(decay sustain release) section can not be shorter than 30 ms (sampling rate is 100 Hz), also, no successive note can be nearer than 30ms. rt(i) = pp(i)+3; else rt(i) = (pp(i)-1)+(p-1); end end if i>1 && rt(i-1)==rt(i) if d(pp(i))>d(pp(i-1)) del = i-1; else del = i; end rt(del) = []; pp(del) = []; pv(del) = []; pm(del) = []; ppp(del) = []; ppv(del) = []; if not(isempty(st)) st(del) = []; end i = i-1; end i = i+1; end rt = {{rt} {pp} {pv} {pm} {ppp} {ppv} {st}};
github
martinarielhartmann/mirtooloct-master
mirspread.m
.m
mirtooloct-master/MIRToolbox/mirspread.m
1,555
utf_8
28dd29263e34084b9b2f6fb8048a491b
function varargout = mirspread(orig,varargin) % S = mirspread(x) calculates the spread of x, which can be either: % - a spectrum (spectral spread), % - an envelope (temporal spread), or % - any histogram. minrms.key = 'MinRMS'; minrms.when = 'After'; minrms.type = 'Numerical'; minrms.default = .01; option.minrms = minrms; specif.option = option; varargout = mirfunction(@mirspread,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirdata')) || isamir(x,'miraudio') x = mirspectrum(x); end type = 'mirscalar'; function S = main(x,option,postoption) if iscell(x) x = x{1}; end y = peaksegments(@spread,get(x,'Data'),... get(x,'Pos'),... get(mircentroid(x,'MaxEntropy',0),'Data')); if isa(x,'mirspectrum') t = 'Spectral spread'; elseif isa(x,'mirenvelope') t = 'Temporal spread'; else t = ['Spread of ',get(x,'Title')]; end S = mirscalar(x,'Data',y,'Title',t); if isstruct(postoption) && strcmpi(get(x,'Title'),'Spectrum') && ... isfield(postoption,'minrms') && postoption.minrms S = after(x,S,postoption.minrms); end function s = spread(d,p,c) s = sqrt( sum((p-c).^2 .* (d/sum(d)) ) ); function S = after(x,S,minrms) r = mirrms(x,'Warning',0); v = mircompute(@trim,get(S,'Data'),get(r,'Data'),minrms); S = set(S,'Data',v); function d = trim(d,r,minrms) r = r/max(max(r)); pos = find(r<minrms); for i = 1:length(pos) d{pos(i)} = NaN; end d = {d};
github
martinarielhartmann/mirtooloct-master
mirevalaudiofile.m
.m
mirtooloct-master/MIRToolbox/mirevalaudiofile.m
3,801
utf_8
c09f3cb5a3481874003dc3510acecedf
function v = mirevalaudiofile(d,file,sampling,lg,size,struc,istmp,index,single,name,ch) % Now let's perform the analysis (or analyses) on the different files. % If d is a structure or a cell array, evaluate each component % separately. if isstruct(d) v = struct; if istmp struc.tmp = struct; end isstat = isfield(d,'Stat'); if isstat d = rmfield(d,'Stat'); end fields = fieldnames(d); for fi = 1:length(fields) fieldname = fields{fi}; field = d.(fieldname); display(['*******',fieldname,'******']); if isstat if isa(field,'mirstruct') field = set(field,'Stat',1); elseif isa(field,'mirdesign') field = mirstat(field,'FileNames',0); else field.Stat = 1; end end res = mirevalaudiofile(field,file,sampling,lg,size,struc,istmp,index,... single,fieldname,ch); if not(isempty(single)) && not(isequal(single,0)) && ... iscell(res) && isa(field,'mirdesign') res = res{1}; end v.(fieldname) = res; if istmp struc.tmp.(fieldname) = res; end if fi == 1 if isfield(res,'Class') v.Class = res.Class; v.(fieldname) = rmfield(res,'Class'); end end end if isfield(v,'tmp') v = rmfield(v,'tmp'); end elseif iscell(d) l = length(d); v = cell(1,l); for j = 1:l v{j} = mirevalaudiofile(d{j},file,sampling,lg,size,struc,istmp,index,... single,[name,num2str(j)],ch); end elseif isa(d,'mirstruct') && isempty(get(d,'Argin')) mirerror('MIRSTRUCT','You should always use tmp fields when using mirstruct. Else, just use struct.'); elseif get(d,'SeparateChannels') v = cell(1,ch); for i = 1:ch d = set(d,'File',file,'Sampling',sampling,'Length',lg,'Size',size,... 'Eval',1,'Index',index,'Struct',struc,'Channel',i); % For that particular file or this particular feature, let's begin the % actual evaluation process. v{i} = evaleach(d,single,name); % evaleach performs a top-down traversal of the design flowchart. end v = combinechannels(v); else d = set(d,'File',file,'Sampling',sampling,'Length',lg,'Size',size,... 'Eval',1,'Index',index,'Struct',struc); dl = get(d,'FrameLength'); if length(dl)>1 v = cell(1,length(dl)); for i = 1:length(dl) d = set(d,'Scale',i); v{i} = evaleach(d,single,name); end v = combinescales(v); else % For that particular file or this particular feature, let's begin the % actual evaluation process. v = evaleach(d,single,name); % evaleach performs a top-down traversal of the design flowchart. end end function y = combinechannels(c) y = c{1}; v = get(y,'Data'); for h = 2:length(c) d = get(c{h},'Data'); for i = 1:length(d) if isa(y,'mirmidi') d{i}(:,3) = h; v{i} = sortrows([v{i};d{i}]); else for j = 1:length(d{i}) v{i}{j}(:,:,h) = d{i}{j}; end end end end y = set(y,'Data',v); function y = combinescales(s) y = s{1}; fp = get(y{1},'FramePos'); fp = fp{1}; for j = 1:length(y) v = get(y{j},'Data'); for h = 2:length(s) d = get(s{h}{j},'Data'); for i = 1:length(d) v{i}{h} = d{i}{1}; end if j == 1 fph = get(s{h}{j},'FramePos'); fp{h} = fph{1}{1}; end end y{j} = set(y{j},'Data',v,'FramePos',{fp}); end
github
martinarielhartmann/mirtooloct-master
mirread.m
.m
mirtooloct-master/MIRToolbox/mirread.m
4,072
utf_8
ed5bcdb732a2c0efcfddd1c0f256ce5d
function [d,tp,fp,f,l,b,n,ch] = mirread(extract,orig,load,folder,verbose) % Read the audio file ORIG, at temporal position indicated by EXTRACT. If % EXTRACT is empty, all the audio file is loaded. % If LOAD is set to 0, just the meta-data is collected, and the actual % audio data is not taken into consideration. If it is set to 1, the % data are loaded from the current directory. If LOAD is a string, it % is considered as the path of the directory. % If FOLDER is set to 1, no error is returned if an audio file cannot be % loaded. % Output: % D is the audio signal, % TP are the temporal positions, % FP are the two extreme temporal positions (used for frame positions), % F is the sampling rate, % L is the duration in seconds, % B is the resolution in number of bits, % N is the file name. % CH are the channel index. if nargin < 5 verbose = 0; end %p = ver('MATLAB'); %if str2num(p.Version) >= 8.3 % [d,tp,fp,f,l,b,n,ch] = mirread2014(extract,orig,load,folder,verbose); % return %end d = {}; f = {}; l = {}; b = {}; tp = {}; fp = {}; n = {}; ch = {}; try [d,f,l,b,tp,fp,n,ch] = audioread(extract,@wavread,orig,load,verbose,folder); catch err.wav = lasterr; try [d,f,l,b,tp,fp,n,ch] = audioread(extract,@auread,orig,load,verbose,folder); catch err.au = lasterr; try [d,f,l,b,tp,fp,n,ch] = audioread(extract,@mp3read,orig,load,verbose,folder); catch err.mp3 = lasterr; try [d,f,l,b,tp,fp,n,ch] = audioread(extract,@aiffread,orig,load,verbose,folder); catch err.aiff = lasterr; if length(orig)>4 && strcmpi(orig(end-3:end),'.bdf') try [d,f,l,b,tp,fp,n,ch] = audioread(extract,@bdfread,orig,load,verbose,folder); catch if not(strcmp(err.wav(1:11),'Error using') && folder) misread(orig, err); end end else if not(strcmp(err.wav(1:11),'Error using') && folder) misread(orig, err); end end end end end end function [d,f,l,b,tp,fp,n,ch] = audioread(extract,reader,file,load,verbose,folder) n = file; if folder file = ['./',file]; end if load if isempty(extract) [s,f,b] = reader(file); else [unused,f,b] = reader(file,1); s = reader(file,extract(1:2)); if length(extract) > 2 s = s(:,extract(3)); end end if verbose disp([file,' loaded.']); end d{1} = reshape(s,size(s,1),1,size(s,2)); %channels along dim 3 ch = 1:size(s,2); if isempty(extract) tp{1} = (0:size(s,1)-1)'/f; else tp{1} = (extract(1)-1+(0:size(s,1)-1))'/f; end l{1} = (size(s,1)-1)/f; if isempty(s) fp{1} = 0; else fp{1} = tp{1}([1 end]); end else if isequal(reader,@mp3read) [dsize,f,b] = reader(file,'size'); else [unused,f,b] = reader(file,1); dsize = reader(file,'size'); end d = dsize(1); l = d/f; tp = {}; fp = {}; ch = dsize(2); end function [y,fs,nbits] = bdfread(file,check) DAT = openbdf(file); NRec = DAT.Head.NRec; if not(length(check)==2) b = readbdf(DAT,1); y = length(b.Record(43,:)) * NRec; else y = []; if mirwaitbar handle = waitbar(0,'Loading BDF channel...'); else handle = 0; end for i = 1:NRec b = readbdf(DAT,i); y = [y;b.Record(43,:)']; if handle waitbar(i/NRec,handle); end end if handle delete(handle) end end fs = DAT.Head.SampleRate(43); nbits = NaN; function misread(file,err) display('Here are the error message returned by each reader:'); display(err.wav); display(err.au); display(err.mp3); display(err.aiff); mirerror('MIRREAD',['Cannot open file ',file]);
github
martinarielhartmann/mirtooloct-master
mirregularity.m
.m
mirtooloct-master/MIRToolbox/mirregularity.m
3,324
utf_8
70fbd83568c0298bdb4eb4e09a40f8c2
function varargout = mirregularity(orig,varargin) % i = mirregularity(x) calculates the irregularity of a spectrum, i.e., % the degree of variation of the successive peaks of the spectrum. % Specification of the definition of irregularity: % mirregularity(...,'Jensen') is based on (Jensen, 1999), % where the irregularity is the sum of the square of the % difference in amplitude between adjoining partials. % (Default approach) % mirregularity(...,'Krimphoff') is based on (Krimphoff et al., 1994), % where the irregularity is the sum of the amplitude minus the % mean of the preceding, same and next amplitude. % If the input x is not already a spectrum with peak extracted, the peak % picking is performed prior to the calculation of the irregularity. % In this case the 'Contrast' parameter used in mirpeaks can be % modified, and is set by default to .1. % % [Krimphoff et al. 1994] J. Krimphoff, S. McAdams, S. Winsberg, % Caracterisation du timbre des sons complexes. II Analyses % acoustiques et quantification psychophysique. Journal de Physique % IV, Colloque C5, Vol. 4. 1994. % [Jensen, 1999] K. Jensen, Timbre Models of Musical Sounds, Ph.D. % dissertation, University of Copenhagen, Rapport Nr. 99/7. meth.type = 'String'; meth.default = 'Jensen'; meth.choice = {'Jensen','Krimphoff'}; option.meth = meth; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = .01; option.cthr = cthr; specif.option = option; varargout = mirfunction(@mirregularity,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirdata')) || isamir(x,'miraudio') x = mirspectrum(x); end if not(haspeaks(x)) x = mirpeaks(x,'Reso','SemiTone','Contrast',option.cthr); %% FIND BETTER end type = 'mirscalar'; function o = main(x,option,postoption) if iscell(x) x = x{1}; end m = get(x,'PeakVal'); p = get(x,'PeakPos'); y = cell(1,length(m)); for h = 1:length(m) y{h} = cell(1,length(m{h})); for k = 1:length(m{h}) y{h}{k} = zeros(size(m{h}{k})); for j = 1:size(m{h}{k},3) for l = 1:size(m{h}{k},2) state = warning('query','MATLAB:divideByZero'); warning('off','MATLAB:divideByZero'); mm = m{h}{k}{1,l,j}; pp = p{h}{k}{1,l,j}; [pp oo] = sort(pp); % Sort peaks in ascending order of x abscissae. mm = mm(oo); if strcmpi(option.meth,'Jensen') y{h}{k}(1,l,j) = sum((mm(2:end,:)-mm(1:end-1,:)).^2)... ./sum(mm.^2); elseif strcmpi(option.meth,'Krimphoff') avrg = filter(ones(3,1),1,mm)/3; y{h}{k}(1,l,j) = log10(sum(abs(mm(2:end-1,:)-avrg(3:end)))); end warning(state.state,'MATLAB:divideByZero'); if isnan(y{h}{k}(1,l,j)) y{h}{k}(1,l,j) = 0; end end end end end if isa(x,'mirspectrum') t = 'Spectral irregularity'; else t = ['Irregularity of ',get(x,'Title')];; end i = mirscalar(x,'Data',y,'Title',t); o = {i,x};
github
martinarielhartmann/mirtooloct-master
mirduration.m
.m
mirtooloct-master/MIRToolbox/mirduration.m
2,222
utf_8
8e5afd3732c22e6a8810ac31d3a9464e
function varargout = mirduration(orig,varargin) % a = mirduration(x) estimates the duration of each note. % Optional arguments: % mirduration(...,'Contrast',c) specifies the 'Contrast' parameter % used in mironsets for event detection through peak picking. % Same default value as in mironsets. % mirduration(...,'Single') only selects one attack and release phase in % sthe ignal (or in each segment). cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = .3; option.cthr = cthr; single.key = 'Single'; single.type = 'Boolean'; single.default = 0; option.single = single; log.key = 'LogOnset'; log.type = 'Boolean'; log.default = 0; option.log = log; minlog.key = 'MinLog'; minlog.type = 'Integer'; minlog.default = 0; option.minlog = minlog; specif.option = option; varargout = mirfunction(@mirduration,orig,varargin,nargout,specif,@init,@main); function [o type] = init(x,option) o = mironsets(x,'Attack','Release','Contrast',option.cthr,'Single',option.single,... 'Log',option.log,'MinLog',option.minlog,... 'Filter','Normal','AcrossSegments'); type = mirtype(x); function du = main(o,option,postoption) if iscell(o) o = o{1}; end pa = get(o,'AttackPos'); pr = get(o,'ReleasePos'); d = get(o,'Data'); t = get(o,'Pos'); [sl fp] = mircompute(@algo,pa,pr,d,t); %fp = mircompute(@frampose,pru); du = mirscalar(o,'Data',sl,'FramePos',fp,'Title','Duration'); du = {du,o}; function fp = frampose(pr) if isempty(pr) fp = []; return end pr = pr{1}; fp = pr; function [du fp] = algo(pa,pr,d,t) if isempty(pa) du = []; fp = []; return end pa = pa{1}; pr = pr{1}; du = zeros(1,length(pa)); fp = zeros(2,length(pa)); for i = 1:length(pa) [mv mp] = max(d(pa(i):pr(2,i))); mp = pa(i) + mp - 1; f1 = find(d(mp:-1:1) < mv * .4,1); if isempty(f1) t1 = t(pa(i)); else t1 = t(mp - f1); end f2 = find(d(mp:pr(2,i)) < mv * .4,1); if isempty(f2) t2 = t(pr(2,i)); else t2 = t(mp + f2); end du(i) = t2 - t1; fp(:,i) = [t1;t2]; end
github
martinarielhartmann/mirtooloct-master
mireventdensity.m
.m
mirtooloct-master/MIRToolbox/mireventdensity.m
3,309
utf_8
6c96ecdc4004805119c526b5425c5e3b
function varargout = mireventdensity(x,varargin) % e = mireventdensity(x) estimate the mean frequency of events (i.e., how % many note onsets per second) in the temporal data x. % Optional arguments: Option1, Option2 % Tuomas Eerola, 14.08.2008 % normal.type = 'String'; normal.choice = {'Option1','Option2'}; normal.default = 'Option1'; option.normal = normal; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [10 1]; option.frame = frame; specif.option = option; %specif.eachchunk = 'Normal'; specif.combinechunk = {'Average','Concat'}; specif.nochunk = 1; varargout = mirfunction(@mireventdensity,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if isamir(x,'mirenvelope') if ~isframed(x) && option.frame.length.val x = mirframe(x,option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend); end else if option.frame.length.val x = mironsets(x, 'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend); else x = mironsets(x); end end type = 'mirscalar'; function e = main(o,option,postoption) if iscell(o) o = o{1}; end sr = get(o,'Sampling'); p = mirpeaks(o); %%%%<<<<<<< MORE OPTIONS HERE % And what is peaks already computed? p = o? pv = get(p,'PeakVal'); v = mircompute(@algo,pv,o,option,sr); e = mirscalar(o,'Data',v,'Title','Event density','Unit','per second'); e = {e o}; function e = algo(pv,o,option,sr) nc = size(o,2); nch = size(o,3); e = zeros(1,nc,nch); % for i = 1:nch % for j = 1:nc % if option.root % e(1,j,i) = norm(d(:,j,i)); % else % disp('do the calc...') % % e(1,j,i) = d(:,j,i)'*d(:,j,i); % %tmp = mironsets(d,'Filterbank',10,'Contrast',0.1); % Change by TE, was only FB=20, no other params % e2 = mirpeaks(e) % [o1,o2] = mirgetdata(e); % e(1,j,i) = length(o2)/mirgetdata(mirlength(d)); % end % end % end for i = 1:nch for j = 1:nc e(1,j,i) = length(pv{1,j,i}); if strcmpi(option.normal,'Option1') e(1,j,i) = e(1,j,i) *sr/size(o,1); elseif strcmpi(option.normal,'Option2') pvs = pv{1}; high_pvs = length(find(mean(pvs)>pvs)); e(1,j,i) = high_pvs(1,j,i) *sr/size(o,1); % only those which are larger than mean end end end %function [y orig] = eachchunk(orig,option,missing,postchunk) %y = mireventdensity(orig,option); %function y = combinechunk(old,new) %do = mirgetdata(old); %dn = mirgetdata(new); %y = set(old,'ChunkData',do+dn);
github
martinarielhartmann/mirtooloct-master
mirentropy.m
.m
mirtooloct-master/MIRToolbox/mirentropy.m
2,342
utf_8
cdbe494a127b13af646739742ce96e90
function varargout = mirentropy(x,varargin) % h = mirentropy(a) calculates the relative entropy of a. % (Cf. User's Manual.) % mirentropy(..., ?Center?) centers the input data before % transforming it into a probability distribution. center.key = 'Center'; center.type = 'Boolean'; center.default = 0; option.center = center; minrms.key = 'MinRMS'; minrms.when = 'After'; minrms.type = 'Numerical'; minrms.default = .005; option.minrms = minrms; specif.option = option; varargout = mirfunction(@mirentropy,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if isamir(x,'miraudio') x = mirspectrum(x); end type = 'mirscalar'; function h = main(x,option,postoption) if iscell(x) x = x{1}; end m = get(x,'Data'); v = cell(1,length(m)); for h = 1:length(m) mh = m{h}; if ~iscell(mh) mh = {mh}; end v{h} = cell(1,length(mh)); for k = 1:length(mh) mk = mh{k}; mn = mk; if isa(x,'mirhisto') || isa(x,'mirscalar') mn = mn'; end if option.center mn = center_(mn); end % Negative data is trimmed: mn(mn<0) = 0; % Data is normalized such that the sum is equal to 1. mn = mn./repmat(sum(mn)+repmat(1e-12,... [1 size(mn,2) size(mn,3) size(mn,4)]),... [size(mn,1) 1 1 1]); % Actual computation of entropy v{h}{k} = -sum(mn.*log(mn + 1e-12))./log(size(mn,1)); if isa(x,'mirhisto') || isa(x,'mirscalar') v{h}{k} = v{h}{k}'; end end end t = ['Entropy of ',get(x,'Title')]; h = mirscalar(x,'Data',v,'Title',t); if (isa(x,'miraudio') || ... (isa(x,'mirspectrum') && strcmpi(get(x,'Title'),'Spectrum')) || ... isa(x,'mircepstrum')) && ... isstruct(postoption) && ... isfield(postoption,'minrms') && postoption.minrms h = after(x,h,postoption.minrms); end function h = after(x,h,minrms) r = mirrms(x,'Warning',0); v = mircompute(@trim,get(h,'Data'),get(r,'Data'),minrms); h = set(h,'Data',v); function d = trim(d,r,minrms) r = r/max(max(r)); pos = find(r<minrms); for i = 1:length(pos) d(pos(i)) = NaN; end d = {d};
github
martinarielhartmann/mirtooloct-master
mirauditory.m
.m
mirtooloct-master/MIRToolbox/mirauditory.m
770
utf_8
9e222a34c1f8d97aef449166d6e18b78
function varargout = mirauditory(x,varargin) % Produces the output based on an auditory modelling, of the signal x, % using a gammatone filterbank. % Optional argument: % mirtempo(...,'Filterbank',b) indicates the number of channels in % the filterbank decomposition. % Default value: b = 40. fb.key = 'Filterbank'; fb.type = 'Integer'; fb.default = 40; option.fb = fb; specif.option = option; varargout = mirfunction(@mirauditory,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if isamir(x,'miraudio') x = mirfilterbank(x,'NbChannels',option.fb); x = mirenvelope(x,'Center','Diff','Halfwave','Center'); end type = 'mirenvelope'; function x = main(x,option,postoption)
github
martinarielhartmann/mirtooloct-master
mirlowenergy.m
.m
mirtooloct-master/MIRToolbox/mirlowenergy.m
2,548
utf_8
ab6f593caf368195ea6bd30902781123
function varargout = mirlowenergy(x,varargin) % p = mirlowenergy(f) computes the percentage of frames showing a RMS % energy that is lower than a given threshold. % For instance, for a musical excerpt with some very loud frames and % lots of silent frames, we would get a high low-energy rate. % Optional argument: % mirlowenergy(...,'Threshold',t) expressed as a ratio to the average % energy over the frames. % Default value: t = 1 % mirlowenergy(...,'Frame',l,h) specifies the use of frames of % length l seconds and a hop rate h. % Default values: l = .05 s, h = .5 % mirlowenergy(...,'Root',0) uses mean square instead of root mean % square % mirlowenergy(...,'ASR') computes the Average Silence Ratio, which % corresponds in fact to a RMS without the square-root, and a default % threshold set to t = .5 % [p,e] = mirlowenergy(...) also returns the RMS energy curve. asr.key = 'ASR'; asr.type = 'Boolean'; asr.default = 0; option.asr = asr; thr.key = 'Threshold'; thr.type = 'Integer'; thr.default = NaN; option.thr = thr; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [.05 .5]; option.frame = frame; specif.option = option; specif.combinechunk = {'Average',@nothing}; specif.extensive = 1; varargout = mirfunction(@mirlowenergy,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if isamir(x,'miraudio') if isframed(x) x = mirrms(x); else x = mirrms(x,'Frame',option.frame.length.val,option.frame.length.unit,... option.frame.hop.val,option.frame.hop.unit,... option.frame.phase.val,option.frame.phase.unit,... option.frame.phase.atend); end end type = 'mirscalar'; function e = main(r,option,postoption) if iscell(r) r = r{1}; end if isnan(option.thr) if option.asr option.thr = .5; else option.thr = 1; end end v = mircompute(@algo,get(r,'Data'),option.thr,option.asr); fp = mircompute(@noframe,get(r,'FramePos')); e = mirscalar(r,'Data',v,'Title','Low energy','Unit','/1','FramePos',fp); e = {e,r}; function v = algo(d,thr,asr) if asr d = d.^2; end v = sum(d < repmat(thr*mean(d,2),[1 size(d,2) 1])); v = v / size(d,2); function fp = noframe(fp) fp = [fp(1);fp(end)]; function y = nothing(old,new) y = old;
github
martinarielhartmann/mirtooloct-master
mirmean.m
.m
mirtooloct-master/MIRToolbox/mirmean.m
2,762
utf_8
6ba3411721923cf88292d17bf0aa2c30
function varargout = mirmean(f,varargin) % m = mirmean(f) returns the mean along frames of the feature f % % f can be a structure array composed of features. In this case, % m will be structured the same way. if isa(f,'mirstruct') data = get(f,'Data'); for fi = 1:length(data) data{fi} = mirmean(data{fi}); end varargout = {set(f,'Data',data)}; elseif isstruct(f) fields = fieldnames(f); for i = 1:length(fields) field = fields{i}; stat.(field) = mirmean(f.(field)); end varargout = {stat}; else specif.nochunk = 1; varargout = mirfunction(@mirmean,f,varargin,nargout,specif,@init,@main); end function [x type] = init(x,option) type = ''; function m = main(f,option,postoption) if iscell(f) f = f{1}; end if isa(f,'mirhisto') warning('WARNING IN MIRMEAN: histograms are not taken into consideration yet.') m = struct; return end fp = get(f,'FramePos'); ti = get(f,'Title'); if 0 %get(f,'Peaks') if not(isempty(get(f,'PeakPrecisePos'))) stat = addstat(struct,get(f,'PeakPrecisePos'),fp,'PeakPos'); stat = addstat(stat,get(f,'PeakPreciseVal'),fp,'PeakMag'); else stat = addstat(struct,get(f,'PeakPosUnit'),fp,'PeakPos'); stat = addstat(stat,get(f,'PeakVal'),fp,'PeakMag'); end else d = get(f,'Data'); end l = length(d); m = cell(1,l); for i = 1:l dd = d{i}; if iscell(dd) m{i} = cell(1,length(dd)); fpi = cell(1,length(dd)); for j = 1:length(dd) m{i}{j} = zeros(size(dd{j},1),1,size(dd{j},3)); for h = 1:size(dd{j},3) for k = 1:size(dd{j},1) dk = dd{j}(k,:,h); m{i}{j}(k,1,h) = mean(dk(not(isnan(dk)))); end end fpi{j} = [fp{i}{j}(1);fp{i}{j}(end)]; end fp{i} = fpi; elseif size(dd,2) < 2 nonan = find(not(isnan(dd))); dn = dd(nonan); m{i}{1} = mean(dn,2); else %diffp = fp{i}{1}(1,2:end) - fp{i}{1}(1,1:end-1); %if round((diffp(2:end)-diffp(1:end-1))*1000) % Not regular sampling (in mirattacktime for instance) % framesampling = NaN; %else % framesampling = fp{i}{1}(1,2)-fp{i}{1}(1,1); %end dd = mean(dd,4); m{i} = {NaN(size(dd,1),1,size(dd,3))}; for k = 1:size(dd,1) for l = 1:size(dd,3) dk = dd(k,:,l); nonan = find(not(isnan(dk))); if not(isempty(nonan)) dn = dk(nonan); m{i}{1}(k,1,l) = mean(dn,2); end end end end end m = mirscalar(f,'Data',m,'Title',['Average of ',ti],'FramePos',fp);
github
martinarielhartmann/mirtooloct-master
mirattacks.m
.m
mirtooloct-master/MIRToolbox/mirattacks.m
613
utf_8
3ca968e23cc9edf7dec8557116e3993e
function varargout = mirattacks(orig,varargin) % Obsolete function, replaced by mironsets(...,'Attacks',...) aver.key = 'Smooth'; aver.type = 'Integer'; aver.default = 20; option.aver = aver; single.key = 'Single'; single.type = 'Boolean'; single.default = 0; option.single = single; specif.option = option; varargout = mirfunction(@mirattacks,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) x = mironsets(x,'Attack',option.aver,'Single',option.single); type = mirtype(x); function a = main(a,option,postoption)
github
martinarielhartmann/mirtooloct-master
mirkey.m
.m
mirtooloct-master/MIRToolbox/mirkey.m
1,998
utf_8
5fe99cbe0e09716f81aedf4ef572a1a1
function varargout = mirkey(orig,varargin) % k = mirkey(x) estimates the key. % Optional argument: % mirkey(...,'Total',m) selects not only the most probable key, but % the m most probable keys. % The other parameter 'Contrast' related to mirpeaks can be specified % here (see help mirchromagram). % The optional parameters 'Weight' and 'Triangle' related to % mirchromagram can be specified here (see help mirchromagram). % [k,ks] = mirkey(...) also returns the key clarity, corresponding here % to the key strength associated to the best candidate. % [k,ks,ksc] = mirkey(...) also displays the key strength curve used for % the key estimation and shows in particular the peaks corresponding % to the selected key(s). tot.key = 'Total'; tot.type = 'Integer'; tot.default = 1; option.tot = tot; thr.key = 'Contrast'; thr.type = 'Integer'; thr.default = .1; option.thr = thr; wth.key = 'Weight'; wth.type = 'Integer'; wth.default = .5; option.wth = wth; tri.key = 'Triangle'; tri.type = 'Boolean'; tri.default = 0; option.tri = tri; specif.option = option; specif.defaultframelength = 1; specif.defaultframehop = .5; varargout = mirfunction(@mirkey,orig,varargin,nargout,specif,@init,@main); function [p type] = init(x,option) if not(isamir(x,'mirkeystrength')) x = mirkeystrength(x,'Weight',option.wth,'Triangle',option.tri); end p = mirpeaks(x,'Total',option.tot,'Contrast',option.thr); type = {'mirscalar','mirscalar','mirkeystrength'}; function k = main(p,option,postoption) if iscell(p) p = p{1}; end pc = get(p,'PeakPos'); pv = get(p,'PeakMaxVal'); pm = get(p,'PeakMode'); k = mirscalar(p,'Data',pc,'Mode',pm,'Title','Key',... 'Legend',{'C','C#','D','D#','E','F','F#','G','G#','A','A#','B'}); m = mirscalar(p,'Data',pv,'Title','Key clarity','MultiData',{}); k = {k m p};
github
martinarielhartmann/mirtooloct-master
mirmfcc.m
.m
mirtooloct-master/MIRToolbox/@mirmfcc/mirmfcc.m
5,499
utf_8
9235c66ed6553be6f816a0f4e08074f4
function varargout = mirmfcc(orig,varargin) % c = mirmfcc(a) finds the Mel frequency cepstral coefficients (ceps), % a numerical description of the spectrum envelope. % % Requires the Auditory Toolbox. % % Optional arguments: % c = mirmfcc(...,'Rank',N) computes the coefficients of rank(s) N % (default: N = 1:13). Beware that the coefficient related to the % average energy is by convention here of rank 0. This zero value % can be included to the array N as well. % If a is a frame decomposition, the temporal evolution of the MFCC, % along the successive frames, is returned. In this case, a second % option is available: % mirmfcc(...,'Delta',d) performs d temporal differentiations of % the coefficients, also called delta-MFCC (for d = 1) or % delta-delta-MFCC (for d = 2). % mirmfcc(...,'Delta') corresponds to mirmfcc(...,'Delta',1) % Optional arguments related to the delta computation: % mirmfcc(...,'Radius',r) specifies, for each frame, the number of % successive and previous neighbouring frames taken into % consideration for the least-square approximation. % Usually 1 or 2. % Default value: 2. nbbands.key = 'Bands'; nbbands.type = 'Integer'; nbbands.default = 40; option.nbbands = nbbands; rank.key = 'Rank'; rank.type = 'Integer'; rank.default = 1:13; option.rank = rank; delta.key = 'Delta'; delta.type = 'Integer'; delta.default = 0; delta.keydefault = 1; option.delta = delta; radius.key = 'Radius'; radius.type = 'Integer'; radius.default = 2; option.radius = radius; specif.option = option; varargout = mirfunction(@mirmfcc,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if isamir(x,'miraudio') || isamir(x,'mirspectrum') x = mirspectrum(x,'Mel','log','Bands',option.nbbands); end type = 'mirmfcc'; function c = main(orig,option,postoption) if iscell(orig) orig = orig{1}; end if isa(orig,'mirmfcc') c = orig; if option.rank magn = get(c,'Data'); rank = get(c,'Rank'); for h = 1:length(magn) for k = 1:length(magn{h}) m = magn{h}{k}; r = rank{h}{k}; r1 = r(:,1,1); range = find(ismember(r1,option.rank)); magn{h}{k} = m(range,:,:); rank{h}{k} = r(range,:,:); end end c = set(c,'Data',magn,'Rank',rank); end c = modif(c,option); else c.delta = 0; %disp('Computing Mel frequency cepstral coefficients...'); e = get(orig,'Magnitude'); % The following is largely based on the source code from Auditory Toolbox % (A part that I could not call directly from MIRtoolbox) % (Malcolm Slaney, August 1993, (c) 1998 Interval Research Corporation) try MakeERBFilters(1,1,1); % Just to be sure that the Auditory Toolbox is installed catch error(['ERROR IN MIRFILTERBANK: Auditory Toolbox needs to be installed.']); end dc = cell(1,length(e)); rk = cell(1,length(e)); for h = 1:length(e) dc{h} = cell(1,length(e{h})); rk{h} = cell(1,length(e{h})); for i = 1:length(e{h}) ei = e{h}{i}; totalFilters = size(ei,3); %Number of mel bands. % Figure out Discrete Cosine Transform. We want a matrix % dct(i,j) which is totalFilters x cepstralCoefficients in size. % The i,j component is given by % cos( i * (j+0.5)/totalFilters pi ) % where we have assumed that i and j start at 0. mfccDCTMatrix = 1/sqrt(totalFilters/2)*... cos(option.rank' * ... (2*(0:(totalFilters-1))+1) * ... pi/2/totalFilters); rank0 = find(option.rank == 0); mfccDCTMatrix(rank0,:) = mfccDCTMatrix(rank0,:) * sqrt(2)/2; ceps = zeros(size(mfccDCTMatrix,1),size(ei,2)); for j = 1:size(ei,2) ceps(:,j) = mfccDCTMatrix * permute(ei(1,j,:),[3 1 2]); end dc{h}{i} = ceps; rk{h}{i} = repmat(option.rank(:),[1 size(ceps,2) size(ceps,3)]); end end c = class(c,'mirmfcc',mirdata(orig)); c = purgedata(c); c = set(c,'Title','MFCC','Abs','coefficient ranks','Ord','magnitude',... 'Data',dc,'Rank',rk); c = modif(c,option); end c = {c orig}; function c = modif(c,option) d = get(c,'Data'); fp = get(c,'FramePos'); t = get(c,'Title'); if option.delta M = option.radius; for k = 1:option.delta for h = 1:length(d) for i = 1:length(d{h}) nc = size(d{h}{i},2)-2*M; di = zeros(size(d{h}{i},1),nc); for j = 1:M di = di + j * (d{h}{i}(:,M+j+(1:nc)) ... - d{h}{i}(:,M-j+(1:nc))); end di = di / 2 / sum((1:M).^2); % MULTIPLY BY 2 INSTEAD OF SQUARE FOR NORMALIZATION ? d{h}{i} = di; fp{h}{i} = fp{h}{i}(:,M+1:end-M); end end t = ['Delta-',t]; end end c = set(c,'Data',d,'FramePos',fp,'Delta',get(c,'Delta')+option.delta,... 'Title',t);
github
martinarielhartmann/mirtooloct-master
mirkeysom.m
.m
mirtooloct-master/MIRToolbox/@mirkeysom/mirkeysom.m
2,211
utf_8
fb4c7b52a6cc328421592d39e5568220
function varargout = mirkeysom(orig,varargin) % ks = mirkeysom(x) projects a chromagram on a self-organizing map. % Creates a pseudocolor map showing the projection of chromagram onto a % self-organizing map trained with the Krumhansl-Kessler profiles (modified % for chromagrams). Colors correspond to Pearson correlation values. % References: % Toiviainen, P. & Krumhansl, C. L. (2003). Measuring and modeling % real-time responses to music: the dynamics of tonality induction. % Perception, 32(6), 741-766. % Krumhansl, C. L., & Toiviainen, P. (2001) Tonal cognition. % In R. J. Zatorre & I. Peretz (Eds.), The Biological Foundations of Music. % Annals of the New York Academy of Sciences. % filename.key = 'File'; % filename.type = 'String'; % filename.default = 0; % option.filename = filename; specif.option = struct; specif.defaultframelength = 1; specif.defaultframehop = .5; varargout = mirfunction(@mirkeysom,orig,varargin,nargout,specif,@init,@main); function [c type] = init(orig,option) c = mirchromagram(orig,'Normal'); type = 'mirkeysom'; function s = main(c,option,postoption) if iscell(c) c = c{1}; end load keysomaudiodata; m = get(c,'Magnitude'); disp('Projecting the chromagram to a self-organizing map...') z = cell(1,length(m)); p = cell(1,length(m)); for i = 1:length(m) mi = m{i}; if not(iscell(mi)) mi = {mi}; end zi = cell(1,length(mi)); pi = cell(1,length(mi)); for j = 1:length(mi) mj = mi{j}; zj = zeros(24,size(mj,2),size(mj,3),36); pi{j} = zeros(24,size(mj,2),size(mj,3),36); for k = 1:size(mj,2) for l = 1:size(mj,3) for kk=1:36 for ll=1:24 tmp = corr([mj(:,k,l) somw(:,kk,ll)]); zj(ll,k,l,kk) = tmp(1,2); end end end end zi{j} = zj; end z{i} = zi; p{i} = pi; end s = class(struct,'mirkeysom',mirdata(c)); s = purgedata(s); s = set(s,'Title','Key SOM','Abs','','Ord','','Weight',z,'Pos',p); %if option.filename % mov = display(s,option.filename); %else % mov = display(s); %end %s = {s,mov};
github
martinarielhartmann/mirtooloct-master
mirmetre.m
.m
mirtooloct-master/MIRToolbox/@mirmetre/mirmetre.m
52,481
utf_8
1cb56ac02c3f2268bafcc13f3b2a073a
function varargout = mirmetre(orig,varargin) % m = mirmetre(x) provides a detailed description of the hierarchical % metrical structure by detecting periodicities from the onset % detection curve and tracking a broad set of metrical levels. % % When mirmetre is used for academic research, please cite the following % publication: % Lartillot, O., Cereghetti, D., Eliard, K., Trost, W. J., Rappaz, M.-A., % Grandjean, D., "Estimating tempo and metrical features by tracking % the whole metrical hierarchy", 3rd International Conference on % Music & Emotion, Jyv?skyl?, 2013. % % Optional arguments: % mirmetre(...,'Frame',l,h) orders a frame decomposition of window % length l (in seconds) and hop factor h, expressed relatively to % the window length. For instance h = 1 indicates no overlap. % Default values: l = 5 seconds and h = .05 % mirmetre(..., ?Min?, mi) indicates the lowest periodicity taken % into consideration, expressed in bpm. Default value: 24 bpm. % mirmetre(..., ?Max?, ma) specifies the highest periodicity taken % into consideration, expressed in bpm. Default value: Inf, % meaning that no limit is set a priori on the highest % periodicity. % mirmetre(..., ?Contrast?, c) specifies the contrast factor for the % peak picking. Default value: c = 0.05. % mirmetre(..., ?Threshold?, c) specifies the contrast factor for the % peak picking. Default value: c = 0. % % [m,p] = mirmetre(...) also displays the autocorrelation function % leading to the tempo estimation, and shows in particular the % peaks corresponding to the tempo values. frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; %frame.default = [0 0]; frame.default = [5 .05]; option.frame = frame; minres.key = 'MinRes'; minres.type = 'Integer'; minres.default = 10; %.1; option.minres = minres; thr.key = 'Threshold'; thr.type = 'Integer'; thr.default = 0; option.thr = thr; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = .05; option.cthr = cthr; mi.key = 'Min'; mi.type = 'Integer'; mi.default = 24; option.mi = mi; ma.key = 'Max'; ma.type = 'Integer'; ma.default = 1000; %500 option.ma = ma; tol.key = 'Tolerance'; tol.type = 'Integer'; tol.default = .2; option.tol = tol; goto.key = {'Goto'}; goto.type = 'Boolean'; goto.default = 0; option.goto = goto; specif.option = option; varargout = mirfunction(@mirmetre,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if iscell(x) x = x{1}; end if isamir(x,'mirmetre') return end if ~isamir(x,'mirautocor') if isamir(x,'mirenvelope') x = mironsets(x,'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit); else if option.goto sg = 'Goto'; else sg = 'Lartillot'; end x = mironsets(x,'SmoothGate',sg,'MinRes',option.minres,... 'Detect',0,... 'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit); end end x = mirautocor(x,'Min',60/option.ma,'Max',60/option.mi * 2,... 'NormalWindow',0); x = mirpeaks(x,'Total',Inf,... 'Threshold',option.thr,'Contrast',option.cthr,... 'NoBegin','NoEnd',... 'Normalize','Local','Order','Amplitude'); type = 'mirmetre'; function m = main(p,option,postoption) if iscell(p) p = p{1}; end if isamir(p,'mirscalar') m = modif(m,postoption); m = {t}; return end pt = get(p,'PeakPrecisePos'); meters = cell(1,length(pt)); globpms = cell(1,length(pt)); d = get(p,'Data'); pp = get(p,'Pos'); ppp = get(p,'PeakPos'); pv = get(p,'PeakVal'); for j = 1:length(pt) for k = 1:length(pt{j}) ptk = pt{j}{k}; for h = 1:size(ptk,3) mipv = +Inf; mapv = -Inf; for l = 1:length(pv{j}{k}) if min(pv{j}{k}{l}) < mipv mipv = min(pv{j}{k}{l}); end if max(pv{j}{k}{l}) > mapv mapv = max(pv{j}{k}{l}); end end mk = {}; activestruct = []; %% Obsolete, activestruct can be entirely removed. globpm = []; for l = 1:size(ptk,2) % For each successive frame %if ~mod(l,100) % l %end ptl = getbpm(p,ptk{1,l,h}); % Peaks bpms = cell(1,length(mk)); for i2 = 1:length(mk) bpms{i2} = [mk{i2}.lastbpm]; end foundk = zeros(1,length(mk)); active = zeros(1,length(mk)); new = 0; %zeros(1,length(mk)); foundomin = zeros(1,length(mk)); ampli = d{j}{k}(:,l,h); pos = ppp{j}{k}{l}; %% for i = 1:length(ptl) % For each peak if ptl(i) < option.mi continue end if ~find(pos > pos(i)*1.95 & pos < pos(i)*2.05) continue end ptli = ptl(i); delta1 = find(ampli(pos(i)+1:end) < 0,1); if isempty(delta1) delta1 = length(ampli) - pos(i); end delta2 = find(ampli(pos(i)-1:-1:1) < 0,1); if isempty(delta2) delta2 = pos(i) - 1; end ptli1 = getbpm(p,pp{j}{k}(pos(i)+delta1,l)); ptli2 = getbpm(p,pp{j}{k}(pos(i)-delta2,l)); %thri = (1-(pv{j}{k}{l}(i) - mipv)/(mapv - mipv))^2/10 ... % + .1; score = ampli(pos(i)); found = zeros(1,length(mk)); % Is peak in metrical hierarchies? dist = inf(1,length(mk)); indx = nan(1,length(mk)); i2 = 1; while i2 <= length(mk) % For each metrical hierarchy if ~activestruct(i2) || ... ~mk{i2}(1).active || isempty(bpms{i2}) i2 = i2+1; continue end globpmi2 = globpm(i2,end); bpm2 = repmat(globpmi2, [1 length(mk{i2})])... ./ [mk{i2}.lvl]; dist1 = abs(60/ptli - 60./bpm2); dist2 = dist1; if 0 % This short-cut has been toggled off, why? for i3 = 1:length(mk{i2}) if isempty(mk{i2}(i3).function) dist1(i3) = NaN; end end [disti1 indx1] = min(dist1); if disti1 < thri && ... abs(log2(ptli / bpm2(indx1))) < .2 dist(i2) = disti1; indx(i2) = indx1; i2 = i2+1; new = 0; continue end end [disti2 indx2] = min(dist2); dist3 = NaN(1,length(mk{i2})); for i3 = 1:length(mk{i2}) if mk{i2}(i3).timidx(end) == l dist3(i3) = NaN; %unnecessary continue end t3 = find(mk{i2}(i3).timidx == l-1); %simplify if ~isempty(t3) dist3(i3) = abs(60/ptli - ... 60./mk{i2}(i3).bpms(t3)); end end [disti3 indx3] = min(dist3); if disti3 < disti2 dist(i2) = disti3; indx(i2) = indx3; else dist(i2) = disti2; indx(i2) = indx2; end if ~foundk(i2) if abs(log2(ptli / bpm2(indx(i2)))) > .2 %.1 dist(i2) = Inf; indx(i2) = 0; new = 1; % New hierarchy (?) i2 = i2+1; continue else new = 0; end end i2 = i2+1; end [unused order] = sort(dist); for i2 = order if ~activestruct(i2) continue end %if foundk(i2) % thri2 = thri; %else % thri2 = min(thri,.1); %end thri2 = .07; %.01; %.07; if isnan(dist(i2)) || dist(i2) > thri2 continue end % Continuing an existing metrical level. if mk{i2}(indx(i2)).timidx(end) ~= l % Metrical level not extended yet. mk{i2}(indx(i2)).timidx(end+1) = l; mk{i2}(indx(i2)).bpms(end+1) = ptl(i); mk{i2}(indx(i2)).lastbpm = ptli; mk{i2}(indx(i2)).score(end+1) = ... d{j}{k}(ppp{j}{k}{1,l,h}(i),l,h); if foundk(i2) active(i2) = 1; else % Metrical hierarchy not extended yet. if isempty(mk{i2}(indx(i2)).function) if isempty(find(foundk,1)) && ... mk{i2}(indx(i2)).score(end) > .15 %.3 %.15 i3 = find([mk{i2}.lvl] == ... mk{i2}(indx(i2)).ref,1); if ~isempty(mk{i2}(i3).function) mk{i2}(indx(i2)).function = ... [mk{i2}(indx(i2)).reldiv; ... mk{i2}(indx(i2)).ref]; end end else active(i2) = 1; end foundk(i2) = 1; end if ~foundomin(i2) && ... ~isempty(mk{i2}(indx(i2)).function) % Global BPM determined using only the most % dominant level. foundomin(i2) = 1; globpm(i2,l) = ptli * mk{i2}(indx(i2)).lvl; for i3 = 1:size(globpm,1) if globpm(i3,l) == 0 globpm(i3,l) = globpm(i3,l-1); end end end end found(i2) = foundk(i2); end i2 = 1; while i2 <= length(mk) if ~activestruct(i2) globpm(i2,l) = NaN; for i3 = 1:size(globpm,1) if globpm(i3,l) == 0 globpm(i3,l) = globpm(i3,l-1); end end i2 = i2+1; continue end %if found(i2)%%%%%%%%%%%%%%%%%%%%%%%% % i2 = i2+1; % continue %end if ~mk{i2}(1).active i2 = i2+1; continue end [unused ord] = sort(bpms{i2}); orbpms = bpms{i2}(ord); fo = find(orbpms > ptli, 1); if isempty(fo) fo = size(orbpms,2)+1; end % Stored levels slower than candidate slower = []; i3 = fo-1; err = Inf; while i3 > 0 if l - mk{i2}(ord(i3)).timidx(end) > 10 || ... ...mk{i2}(ord(i3)).score(end) < .1 || ... %%%%% To toggle off sometimes? (cf. level 1/6 in the paper) ~isempty(mk{i2}(ord(i3)).complex) i3 = i3-1; continue end if mk{i2}(ord(i3)).reldiv > 0 && ... isempty(mk{i2}(ord(i3)).function) i3 = i3-1; continue end bpm3 = globpm(i2,end) / mk{i2}(ord(i3)).lvl; if 0 %abs(60/ptli - 60/bpm3) > dist(i2) %%%%% To toggle off sometimes? (cf. level 1/6 in the paper) i3 = i3-1; continue end rdiv = round(ptli / bpm3); if rdiv == 1 i3 = i3-1; continue end lvl = mk{i2}(ord(i3)).lvl / rdiv; if ~isempty(find(lvl == [mk{i2}.lvl],1)) i3 = i3-1; continue end if rdiv == 0 || rdiv > 8 || ... abs(60/ptli - ... 60/(globpm(i2,end) / lvl))... > dist(i2) i3 = i3-1; continue end %if 1 %~foundk(i2) div = ptli ./ bpm3; %else % div = [ptli2; ptli1] ./ bpm3; %end %if floor(div(1)) ~= floor(div(2)) % newerr = 0; %else newerr = min(mod(div,1),1-mod(div,1)); %end if ~foundk(i2) thr = .02; else thr = option.tol; end if newerr > thr i3 = i3-1; continue end %if 0 && ~isempty(find([mk{i2}.lvl] > lvl & ... % [mk{i2}.lvl] < mk{i2}(ord(i3)).lvl)) % i3 = i3-1; % continue %end % Candidate level can be % integrated in this metrical % hierarchy if newerr < err if isempty(slower) slower.ref = ord(i3); slower.lvl = lvl; slower.bpm = orbpms(i3); slower.score = mk{i2}(ord(i3)).score(end); slower.rdiv = rdiv; rptli1 = orbpms(i3) * (rdiv - .4); if ptli1 < rptli1 ptli1 = rptli1; end rptli2 = orbpms(i3) * (rdiv + .4); if ptli2 > rptli2 ptli2 = rptli2; end %ptli = mean([ptli1,ptli2]); err = newerr; %break elseif mk{i2}(ord(i3)).lvl / rdiv ... ~= slower.lvl slower.ref = ord(i3); slower.lvl = lvl; slower.rdiv = rdiv; %slower = []; %break end end i3 = i3 - 1; end % Stored levels faster than candidate faster = []; if ~found(i2) i3 = fo; err = Inf; while i3 <= length(orbpms) if l - mk{i2}(ord(i3)).timidx(end) > 10 || ... ~isempty(mk{i2}(ord(i3)).complex) i3 = i3+1; continue end %if ...~foundk(i2) && % isempty(mk{i2}(ord(i3)).function) % i3 = i3+1; % continue %end bpm3 = globpm(i2,end) / mk{i2}(ord(i3)).lvl; %if ~foundk(i2) div = bpm3 ./ [ptli ptli]; %else % div = bpm3 ./ [ptli2;ptli1]; %end rdiv = round(bpm3 / ptli); if rdiv == 1 i3 = i3+1; continue end lvl = mk{i2}(ord(i3)).lvl * rdiv; if ~isempty(find(lvl == [mk{i2}.lvl],1)) i3 = i3+1; continue end if rdiv <= 1 || ... abs(60/ptli - ... 60/(globpm(i2,end) / lvl)) ... > dist(i2) i3 = i3+1; continue end if floor(div(1)) < floor(div(2)) newerr = 0; else newerr = min(min(mod(div,1)),... min(1-mod(div,1))); end if ~foundk(i2) thr = .1; %.01; else thr = option.tol; end if newerr < thr % Candidate level can be % integrated in this metrical % hierarchy if newerr < err if isempty(faster) faster.ref = ord(i3); faster.lvl = lvl; faster.bpm = orbpms(i3); faster.score = mk{i2}(ord(i3)).score(end); faster.rdiv = rdiv; rptli1 = orbpms(i3) / (rdiv + .4); if ptli1 < rptli1 ptli1 = rptli1; end rptli2 = orbpms(i3) / (rdiv - .4); if ptli2 > rptli2 ptli2 = rptli2; end %ptli = mean([ptli1,ptli2]); err = newerr; %break elseif mk{i2}(ord(i3)).lvl * rdiv ... ~= faster.lvl faster.ref = ord(i3); faster.lvl = lvl; faster.rdiv = rdiv; %faster = []; %break end end end i3 = i3 + 1; end end if isempty(slower) && isempty(faster) i2 = i2 + 1; continue elseif isempty(slower) lvl = faster.lvl; rdiv = faster.rdiv; reldiv = rdiv; ref = faster.ref; elseif isempty(faster) lvl = slower.lvl; rdiv = slower.rdiv; reldiv = -rdiv; ref = slower.ref; elseif slower.score < faster.score lvl = faster.lvl; rdiv = faster.rdiv; reldiv = rdiv; ref = faster.ref; else lvl = slower.lvl; rdiv = slower.rdiv; reldiv = -rdiv; ref = slower.ref; end active(i2) = 1; found(i2) = 1; new = 0; l0 = find(lvl == [mk{i2}.lvl]); if isempty(l0) % New metrical level mk{i2}(end+1).lvl = lvl; if isempty(mk{i2}(ref).function) mk{i2}(end).function = []; else same = find(mk{i2}(ref).function(1,:)... *reldiv < 0); saillant = 0; %isempty(same); for i3 = 1:length(same) refdiv = mk{i2}(ref)... .function(1,same(i3)); otherlvl = mk{i2}(ref)... .function(2,same(i3)); other = find([mk{i2}.lvl] ... == otherlvl); if abs(reldiv) < abs(refdiv) intradiv = abs(refdiv/reldiv); if round(intradiv) ~= intradiv continue end if ~isempty(mk{i2}(other).function) otherfunction = ... find(mk{i2}(other).function(1,:)... == refdiv); if ~isempty(otherfunction) mk{i2}(ref)... .function(:,same(i3)) = ... [-reldiv; lvl]; mk{i2}(other).function(:,otherfunction)... = [intradiv; lvl]; end end mk{i2}(end).function = ... [reldiv,-intradiv; ... mk{i2}(ref).lvl,... mk{i2}(other).lvl]; saillant = 2; break elseif mk{i2}(other).timidx(end)... ~= l || ... mk{i2}(other).score(end)... < ampli(pos(i)) saillant = 1; end end if saillant == 1 mk{i2}(end).function = ... [reldiv; mk{i2}(ref).lvl]; mk{i2}(ref).function(:,end+1) = ... [-reldiv; lvl]; elseif saillant == 0 mk{i2}(end).function = []; end end mk{i2}(end).lastbpm = ptli; mk{i2}(end).bpms = ptl(i); mk{i2}(end).timidx = l; mk{i2}(end).score = ampli(pos(i)); mk{i2}(end).ref = mk{i2}(ref).lvl; mk{i2}(end).reldiv = reldiv; if abs(reldiv) == 5 || abs(reldiv) > 6 mk{i2}(end).complex = 1; end if reldiv < 0 && ~isempty(mk{i2}(ref).element) mk{i2}(ref).element = []; mk{i2}(end).element = 1; end coord = [i2 length(mk{i2})]; bpms{i2}(end+1) = ptli; else dist0 = abs(mean([mk{i2}(l0).lastbpm]) - ptl(i)); [unused md] = min(dist0); if mk{i2}(l0(md)).timidx(end) < l mk{i2}(l0(md)).lastbpm = ptli; mk{i2}(l0(md)).bpms(end+1) = ptl(i); mk{i2}(l0(md)).score(end+1) = ampli(pos(i)); mk{i2}(l0(md)).timidx(end+1) = l; elseif score > mk{i2}(l0(md)).score mk{i2}(l0(md)).lastbpm = ptli; mk{i2}(l0(md)).bpms(end) = ptl(i); mk{i2}(l0(md)).score(end) = ampli(pos(i)); end coord = [i2 l0(md)]; end if ~foundk(i2) foundk(i2) = 1; globpm(i2,l) = ptli * mk{i2}(coord(2)).lvl; for i3 = 1:size(globpm,1)-1 if globpm(i3,l) == 0 globpm(i3,l) = globpm(i3,l-1); end end end i2 = i2 + 1; end if i == 1 && (new || ... ~isempty(find(found == -1)) || ... isempty(find(found))) && ... d{j}{k}(ppp{j}{k}{1,l,h}(i),l,h) > .1 %.15) % New metrical hierarchy mk{end+1}.lvl = 1; mk{end}.function = [0;1]; mk{end}.lastbpm = ptli; mk{end}.bpms = ptl(i); mk{end}.timidx = l; mk{end}.score = ... d{j}{k}(ppp{j}{k}{1,l,h}(i),l,h); mk{end}.globpms = []; mk{end}.locked = 0; mk{end}.active = 1; mk{end}.ref = []; mk{end}.element = 1; mk{end}.reldiv = 0; mk{end}.complex = []; %found(end+1) = 1; bpms{end+1} = ptli; foundk(end+1) = 1; globpm(end+1,1:l) = NaN(1,l); globpm(end,l) = ptli; for i3 = 1:size(globpm,1)-1 if globpm(i3,l) == 0 globpm(i3,l) = globpm(i3,l-1); end end %coord = [length(bpms),1]; %found = abs(found); foundk = abs(foundk); active(end+1) = 1; %new(end+1) = 0; foundomin(end+1) = 1; activestruct(end+1) = 1; end end %activestruct(~foundomin) = 0; %% for i = 1:length(mk) %if ~activestruct(i) || ~mk{i}(1).active % globpm(i,l) = NaN; % for i2 = 1:length(mk{i}) % if mk{i}(i2).timidx(end) == l % mk{i}(i2).globpms(end+1) = globpm(i,l) ... % / mk{i}(i2).lvl; % end % end % continue %end %% Should we reactivate that test? %if ~mk{i}(1).active % continue %end %% for i2 = 1:length(mk{i}) if isempty(mk{i}(i2).function) || ... mk{i}(i2).timidx(end) < l continue end if isempty(mk{i}(i2).ref) continue end ref = find([mk{i}.lvl] == mk{i}(i2).ref); if isempty(ref) continue end if isempty(mk{i}(ref).function) || ... (mk{i}(ref).timidx(end) == l && ... mk{i}(ref).score(end) > mk{i}(i2).score(end)) continue end reldiv = mk{i}(i2).reldiv; same = find(mk{i}(ref).function(1,:) * reldiv < 0); for i3 = 1:length(same) refdiv = mk{i}(ref).function(1,same(i3)); otherlvl = mk{i}(ref).function(2,same(i3)); other = find([mk{i}.lvl] == otherlvl); if isempty(other) || ... isempty(mk{i}(other).function) || ... abs(reldiv) >= abs(refdiv) continue end intradiv = abs(refdiv/reldiv); otherfunction = ... find(mk{i}(other).function(1,:)... == -refdiv,1); if isempty(otherfunction) continue end if round(intradiv) == intradiv mk{i}(ref)... .function(:,same(i3)) = ... [-reldiv; mk{i}(i2).lvl]; mk{i}(other).function(:,otherfunction)... = [intradiv; mk{i}(i2).lvl]; mk{i}(i2).function = ... [reldiv,-intradiv; ... mk{i}(ref).lvl, mk{i}(other).lvl]; break elseif mk{i}(other).timidx(end) ~= l || ... mk{i}(other).score(end)... < mk{i}(i2).score(end) mk{i}(i2).function = ... [reldiv; mk{i}(ref).lvl]; mk{i}(ref).function(:,end+1) = ... [-reldiv; mk{i}(i2).lvl]; mk{i}(other).function(:,otherfunction) = []; break end end end if l == 1 || isnan(globpm(i,l-1)) || ~globpm(i,l-1) glo = 0; sco = 0; for i2 = 1:length(mk{i}) if mk{i}(i2).timidx(end) == l && ... ~isempty(mk{i}(i2).function) sco2 = mk{i}(i2).score(end); ind = mk{i}(i2).bpms(end) * mk{i}(i2).lvl; glo = glo + ind * sco2; sco = sco + sco2; end end globpm(i,l) = glo / sco; else glog = log2(globpm(i,l-1)); glodif = 0; sco = 0; mindif = Inf; for i2 = 1:length(mk{i}) if mk{i}(i2).timidx(end) == l && ... ~isempty(mk{i}(i2).function) && ... mk{i}(i2).score(end) > 0 %mk{i}(i2).bpms(end) > 30 globpm2 = mk{i}(i2).bpms(end) ... * mk{i}(i2).lvl; dif = glog - log2(globpm2); sco2 = mk{i}(i2).score(end) / abs(dif); glodif = glodif + dif * sco2; sco = sco + sco2; if abs(dif) < abs(mindif) mindif = dif; end end end if glodif glodif = glodif / sco; end if abs(glodif) > abs(mindif) if glodif * mindif < 0 glodif = 0; else glodif = mindif; end end if abs(glodif) > .05 glodif = .05 * sign(glodif); end globpm(i,l) = globpm(i,l-1) / 2^glodif; end for i2 = 1:length(mk{i}) if mk{i}(i2).timidx(end) == l mk{i}(i2).globpms(end+1) = globpm(i,l) ... / mk{i}(i2).lvl; end end end %% %if 1 %~isempty(find(active,1)) inactive = find(~active); for i = 1:length(inactive) mk{inactive(i)}(1).active = 0; end %end %% i = 1; while i < length(mk) i = i + 1; if mk{i}(1).locked continue end if ~mk{i}(1).active || ~activestruct(i) continue end score1 = 0; for i3 = 1:length(mk{i}) if mk{i}(i3).element nbpms1a = globpm(i,l)/ mk{i}(i3).lvl; nbpms1b = mk{i}(i3).lastbpm; element1 = i3; %lvl1 = mk{i}(i3).lvl; end if mk{i}(i3).score(end) > score1 score1 = mk{i}(i3).score(end); end end i3 = 1; while i3 < i if ~mk{i3}(1).active i3 = i3 + 1; continue end included = 0; score2 = 0; for i2 = 1:length(mk{i3}) if ~isempty(mk{i3}(i2).element) || ... ~isempty(mk{i3}(i2).function) nbpms2a = globpm(i3,l)/ mk{i3}(i2).lvl; nbpms2b = mk{i3}(i2).lastbpm; %lvl2 = mk{i3}(i2).lvl; if abs(60/nbpms1a - 60./nbpms2a) < .01 || ... 0 %abs(60/nbpms1b - 60./nbpms2b) < .01 included = i2; element2 = i2; end end if mk{i3}(i2).score(end) > score2 score2 = mk{i3}(i2).score(end); end end if included if score1 > score2 majo = [i element1]; mino = i3; if length(mk{i3}(1).timidx) > 1 mk{i3}(1).active = 0; i3 = i3 + 1; break; end else majo = [i3 element2]; mino = i; if length(mk{i}(1).timidx) > 1 mk{i}(1).active = 0; i3 = i3 + 1; break; end end for i2 = 1:length(mk{mino}) div = round(mk{majo(1)}(majo(2)).lastbpm ... / mk{mino}(i2).lastbpm); lvl = div * mk{majo(1)}(majo(2)).lvl; i5 = find(lvl == [mk{majo(1)}.lvl],1); if isempty(i5) mk{majo(1)}(end+1).lvl = lvl; mk{majo(1)}(end).lastbpm = mk{mino}(i2).lastbpm; mk{majo(1)}(end).bpms = mk{mino}(i2).bpms; mk{majo(1)}(end).globpms = ... globpm(majo(1), mk{mino}(i2).timidx)... / lvl; mk{majo(1)}(end).timidx = mk{mino}(i2).timidx; mk{majo(1)}(end).score = mk{mino}(i2).score; mk{majo(1)}(end).ref = mk{majo(1)}(majo(2)).lvl; mk{majo(1)}(end).reldiv = div; bpms{majo(1)}(end+1) = mk{mino}(i2).lastbpm; end end if score1 > score2 mk(i) = mk(i3); globpm(i) = globpm(i3); bpms(i) = bpms(i3); end mk(i) = []; globpm(i,:) = []; bpms(i) = []; active(i) = []; %new(i) = []; i = i - 1; break end i3 = i3 + 1; end %for i3 = 1:0 length(mk) % if i == i3 || ~mk{i3}(1).active % continue % end % included = 0; % for i2 = 1:length(mk{i}) % if isempty(mk{i}(i2).function) % continue % end % % nbpms1 = globpm(i,l)/ mk{i}(i2).lvl; % nbpms2 = repmat(globpm(i3,l),[1,size(mk{i3},2)])... % ./ [mk{i3}.lvl]; % for i4 = 1:length(mk{i3}) % if mk{i3}(i4).timidx(end) < l %|| ... % %isempty(mk{i3}(i4).function) % nbpms2(i4) = NaN; % end % end % dist = abs(60/nbpms1 - 60./nbpms2); % i4 = find(dist<.01,1); % if ~isempty(i4) % if isempty(mk{i3}(i4).function) % continue % mk{i}(1).locked = i3; % end % % included = 1; % ratio = mk{i3}(i4).lvl / mk{i}(i2).lvl; % for i4 = 1:length(mk{i}) % lvl = mk{i}(i4).lvl * ratio; % i5 = find(lvl == [mk{i3}.lvl],1); % if isempty(i5) % mk{i3}(end+1).lvl = lvl; % mk{i3}(end).lastbpm = mk{i}(i4).lastbpm; % mk{i3}(end).bpms = mk{i}(i4).bpms; % mk{i3}(end).globpms = globpm(i,mk{i}(i4).timidx) ... % / mk{i}(i4).lvl; % mk{i3}(end).timidx = mk{i}(i4).timidx; % mk{i3}(end).score = mk{i}(i4).score; % mk{i3}(end).ref = mk{i}(i4).ref * ratio; % mk{i3}(end).reldiv = mk{i}(i4).reldiv; % bpms{i3}(end+1) = mk{i}(i4).lastbpm; % else % new.timidx = []; % new.bpms = []; % new.globpms = []; % new.score = []; % for it = 1:l % t2 = find(mk{i3}(i5).timidx... % == it); % t1 = find(mk{i}(i4).timidx... % == it); % if isempty(t1) % if ~isempty(t2) % new.timidx(end+1) = it; % new.bpms(end+1) = ... % mk{i3}(i5).bpms(t2); % new.globpms(end+1) = ... % mk{i3}(i5).globpms(t2); % new.score(end+1) = ... % mk{i3}(i5).score(t2); % end % else % if isempty(t2) || ... % mk{i3}(i5).score(t2) < ... % mk{i}(i4).score(t1) % test = 1; % for i6 = 1:length(mk{i3}) % t3 = find(mk{i3}(i6).timidx == it); % if ~isempty(t3) && ... % abs(60./mk{i3}(i6).bpms(t3) ... % - 60./mk{i}(i4).bpms(t1)) ... % < .01 % test = 0; % break % end % end % else % test = 0; % end % if test % new.timidx(end+1) = it; % new.bpms(end+1) = ... % mk{i}(i4).bpms(t1); % new.globpms(end+1) = ... % mk{i}(i4).globpms(t1); % new.score(end+1) = ... % mk{i}(i4).score(t1); % elseif ~isempty(t2) % new.timidx(end+1) = it; % new.bpms(end+1) = ... % mk{i3}(i5).bpms(t2); % new.globpms(end+1) = ... % mk{i3}(i5).globpms(t2); % new.score(end+1) = ... % mk{i3}(i5).score(t2); % end % end % end % mk{i3}(i5).timidx = new.timidx; % mk{i3}(i5).bpms = new.bpms; % mk{i3}(i5).globpms = new.globpms; % mk{i3}(i5).score = new.score; % end % end % end % end % if included % % meters{i} is completely included into % % meters{i2} % mk(i) = []; % globpm(i,:) = []; % i = i - 1; % break % end %end end end end meters{j}{k} = mk; globpms{j}{k} = globpm; end end dm = purgedata(p); m.autocor = dm; m.globpm = globpms; dm = set(dm,'Data',meters); m = class(m,'mirmetre',mirdata(dm)); function bpm = getbpm(p,ptl) if isa(p,'mirautocor') && not(get(p,'FreqDomain')) bpm = 60./ptl; else bpm = ptl*60; end
github
martinarielhartmann/mirtooloct-master
get.m
.m
mirtooloct-master/MIRToolbox/@mirdesign/get.m
4,242
utf_8
83638fe1ced39af50e3243751684b616
function varargout = get(a,varargin) % GET Get properties from the MIRdesign object and return the value if ischar(varargin{1}) switch varargin{1} case 'Method' varargout = {a.method}; return case 'File' varargout = {a.file}; return case 'FrameLength' if isstruct(a.frame) varargout = {a.frame.length.val}; else varargout = {[]}; end return case 'FrameHop' if isstruct(a.frame) varargout = {a.frame.hop.val}; else varargout = {[]}; end return case 'FramePhase' if isstruct(a.frame) varargout = {a.frame.phase.val}; else varargout = {[]}; end return case 'FrameLengthUnit' if isstruct(a.frame) varargout = {a.frame.length.unit}; else varargout = {[]}; end return case 'FrameHopUnit' if isstruct(a.frame) varargout = {a.frame.hop.unit}; else varargout = {[]}; end return case 'FramePhaseUnit' if isstruct(a.frame) varargout = {a.frame.phase.unit}; else varargout = {[]}; end return case 'FramePhaseAtEnd' if isstruct(a.frame) varargout = {a.frame.phase.atend}; else varargout = {[]}; end return case 'FrameDontChunk' if isstruct(a.frame) varargout = {a.frame.dontchunk}; else varargout = {[]}; end return case 'Segment' varargout = {a.segment}; return case 'ChunkDecomposed' varargout = {a.chunkdecomposed}; return case 'Size' varargout = {a.size}; return case 'Type' varargout = {a.type}; return case 'Chunk' varargout = {a.chunk}; return case 'Eval' varargout = {a.eval}; return case 'Argin' varargout = {a.argin}; return case 'VarArgin' varargout = {a.varargin}; return case 'Specif' varargout = {a.specif}; return case 'InterChunk' varargout = {a.interchunk}; return case 'AcrossChunks' varargout = {a.acrosschunks}; return case 'Option' varargout = {a.option}; return case 'PostOption' varargout = {a.postoption}; return case 'NoChunk' varargout = {a.nochunk}; return case 'Ready' varargout = {a.ready}; return case 'Struct' varargout = {a.struct}; return case 'Stored' varargout = {a.stored}; return case 'Index' varargout = {a.index}; return case 'TmpFile' varargout = {a.tmpfile}; return case 'TmpOf' varargout = {a.tmpof}; return case 'Ascending' varargout = {a.ascending}; return case 'SeparateChannels' varargout = {a.separate}; return case 'Channel' varargout = {a.channel}; return case 'Scale' varargout = {a.scale}; return case 'ChunkSizeFactor' varargout = {a.chunksizefactor}; return end end prop.type = 'String'; prop.position = 2; prop.default = ''; option.prop = prop; specif.option = option; varargout = mirfunction(@get,a,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = ''; function val = main(a,option,postoption) val = get(a,option.prop);