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
ncohn/Windsurf-master
Windsurf_RunXBeach.m
.m
Windsurf-master/Windsurf_RunXBeach.m
14,078
utf_8
003698e6550bf677a8770bbc1144421f
%Windsurf_RunXBeach.m - This code serves to run individual simulations of the XBeach to be used with the Windsurf set of codes for coupled model simulations %Created By: N. Cohn, Oregon State University if project.flag.XB == 1 %only run XBeach if need to %Enter appropriate model directory cd([project.Directory, filesep, 'xbeach']) %Setup relevant input files and grids setup_xbeach_grids(project, waves, grids, run, run_number) if abs(270-waves.D(run_number)) < 45 && waves.Hs(run_number) > 0.1 %dont run morph model if waves are too oblique or too small %Set up waves files setup_xbeach_hydro(run_number, waves, tides, winds, project, grids); %Note super efficient re-writing this file each iteration, but need to do in case morfac or stationary/instationary changes xb_params(project, grids, waves, flow, tides, winds, sed, veg, run_number); %Run XBeach if numel(project.XB.XBExecutable)>3 % this ensures that the variable is not empty if isunix == 1 try %try the exe up to 3 times - there are issues on CENTOS7 that leads to a bang-poll error if EXE is run at the same time system([project.XB.XBExecutable, ' > /dev/null']); catch err try pause(1); system([project.XB.XBExecutable, ' > /dev/null']); catch err pause(1); system([project.XB.XBExecutable, ' > /dev/null']); end end else %hopefully dont have same bang-poll issues on other operating systems, will write out more data to screen without /dev/null command system([project.XB.XBExecutable, ' > NUL 2>&1']); end else %if variable is empty then just try calling the system command, will throw an error if no xbeach executable in path otherwise system('xbeach > command_line_xbeach.txt'); end % pause(0.1); %wait for system to catch up with writing files %Load Outputs [project, run] = load_xbeach_output(project, run, waves, grids, run_number); %If there is an error in the output then re-run xbeach - happens sometimes on Centos7 (not sure why....) if numel(project.twl) < run_number %first just try-reloading output, could be a time waiting issue pause(1); %wait for system to catch up with writing files [project, run] = load_xbeach_output(project, run, waves, grids, run_number); if numel(project.twl) < run_number %if its still an issue... system([project.XB.XBExecutable, ' > command_line_xbeach.txt']); pause(10); %wait for system to catch up with writing files [project, run] = load_xbeach_output(project, run, waves, grids, run_number); end end run.startz = dlmread('z.dep'); %probably orig z is loaded in somewhere in history, so this is a bit I/O intensive. But should be limited for 1D sims %run.init_z = grids.XZfinal(:,2); %probably orig z is loaded in somewhere in history, so this is a bit I/O intensive. But should be limited for 1D sims run.z(1:10) = run.startz(1:10); %Correct offshore since there can be sediment accumulation at offshore extent of the model grid which can mess up long term simulations (though this does pose some mass balance issues... %Total Water Level Calc if waves.XB.useStockdon == 1 || isnan(project.twl(run_number)) == 1 project.twl(run_number) = StockdonTWL(run_number, tides, waves, run, grids); end %Flag to say that clear xbeach was actually run - useful for debugging run.xbuse = 1; %elevation change over simulation run.wave_dz = run.z(:)-run.startz(:); else %if waves are too oblique, then dont run xbeach and just pass on relevant into to coupler project.twl(run_number) = tides.waterlevel(run_number); %here just assume the TWL is just the tides, since unclear what runup is under very steep angle waves - Stockdon likely not appropriate run.xbuse = 0; %flag to say xbeach was not run run.wave_dz = zeros(size(run.z(:))); run.Hmean = zeros(size(run.z(:))); end else %if the run_type is set to not run XBeach, then just pass on z info and TWL project.twl(run_number) = StockdonTWL(run_number, tides, waves, run, grids); run.xbuse = 0; run.wave_dz = zeros(size(run.z(:))); run.Hmean = zeros(size(run.z(:))); end %want to make sure that this output is not re-used if simulation crashes if project.XB.NetCDF == 0 && project.flag.XB == 1 delete('zb.dat'); end %clear all un-needed variables clear iuse Z_OUT xbuse fid zs zs2 new_wave_angle new_wind_angle zb zb2 Hmean2 zsmax2 %SUB-FUNCTIONS function setup_xbeach_hydro(run_number, waves, tides, winds, project, grids) %convention for the wave angles up to this point should have been that 0 is shore normal but for xbeach convention is that 270 is directed onshore wave_angle = wrapTo360(waves.D(run_number)); %This is the main code which sets up relevant input files at each time for xbeach and runs the simulations if wave_angle>(270-45) && wave_angle<(270+45) || run_number == 1 %only run simulation if waves are not super oblique % if regimes.wave_type(run_number) == 1 %use instationary solver %set up JONSWAP wave file for XBeach outputSpectraFileName = ['spectra.spec']; fid = fopen(outputSpectraFileName, 'w'); fprintf(fid,'%s\n',['Hm0= ', num2str(waves.Hs(run_number))]); if waves.Tp(run_number)>0 %need to check to make sure dont have infinite frequency fprintf(fid,'%s\n',['fp= ', num2str(1/waves.Tp(run_number))]); else fprintf(fid,'%s\n',['fp= 0']); end fprintf(fid,'%s\n',['mainang= ', num2str(wave_angle)]); fclose(fid); % else %set up stationary wave file for XBeach % outputSpectraFileName = ['spectra.spec']; % fid = fopen(outputSpectraFileName, 'w'); % fprintf(fid,'%s\n',['Hrms= ', num2str(waves.WaveRuns(run_number,5))]); % fprintf(fid,'%s\n',['Trep= ', num2str(waves.WaveRuns(run_number,2))]); % fprintf(fid,'%s\n',['dir0= ', num2str(wave_angle)]); % fclose(fid); % end %export new water level file for XBeach fid = fopen('waterlevel.inp', 'w'); fprintf(fid, '%s\n', ['0 ', num2str(tides.waterlevel(run_number))]); fprintf(fid, '%s\n', [num2str(project.timeStep+project.XB.hydro_spinup), ' ', num2str(tides.waterlevel(run_number))]); fclose(fid); %export new wind file for XBeach - currently does this whether or not wind is actually used in XB new_wind_angle = wrapTo360(winds.winddir(run_number)+270); fid = fopen('winds.inp', 'w'); fprintf(fid, '%s\n', ['0 ', num2str(winds.windspeed(run_number)), ' ', num2str(new_wind_angle)]); fprintf(fid, '%s\n', [num2str(project.timeStep+project.XB.hydro_spinup), ' ', num2str(winds.windspeed(run_number)), ' ', num2str(new_wind_angle)]); fclose(fid); end end function TWL = StockdonTWL(run_number, tides, waves, run, grids) %Geometry of high and low tide low_tide = prctile(tides.waterlevel, 10); %first approximation at high/low tide high_tide = prctile(tides.waterlevel, 90); xlow = linterp(run.z(:), grids.XGrid(:), low_tide); xhigh = linterp(run.z(:), grids.XGrid(:), high_tide); Bf = abs(high_tide-low_tide)/abs(xhigh-xlow); %Calculate wave parameters and runup Lo = 9.81*waves.Tp(run_number)*waves.Tp(run_number)/(2*pi); Ho = waves.Hs(run_number); R2 = 1.1*(0.35*Bf*sqrt(Ho*Lo)+sqrt(Ho*Lo*(0.563*Bf*Bf+0.004))/2); TWL = tides.waterlevel(run_number)+R2; end function [project, run] = load_xbeach_output(project, run, waves, grids,run_number) %Setup variables loop = 1; count = 0; %Loop through repeatedly in case output does not load on first try, can be %due to slow writing of data from XB while loop == 1 try %Load in morphology if project.XB.NetCDF ==1 zb = ncread('xboutput.nc', 'zb'); zb = zb(:); %convert to column vector if numel(zb)> grids.nx zb = zb(end-grids.nx+1:end); end else %if its a fortran file - dont know why but sometimes there are issues with fortran versions... clear zb2 xbdata = xb_read_dat('zb.dat'); zb2(:,:) = xbdata.data(2).value(:,1,:); zb = zb2'; %for some reason size conventions for fortran and netcdf are opposite? zb = zb(end-grids.nx+1:end); end run.z = zb(:); %Load in waves if project.XB.NetCDF ==1 Hmean = ncread('xboutput.nc', 'H_mean'); Hmean = Hmean(:); %convert to column vector if numel(Hmean)> grids.nx Hmean = Hmean(end-grids.nx+1:end); end else try clear Hmean2 xbdata = xb_read_dat('H_mean.dat'); Hmean(:,:) = xbdata.data(2).value(:,1,:); Hmean = Hmean'; catch err Hmean = zeros(size(zb2)); end end run.Hmean = Hmean(:); %Load in water level if project.XB.NetCDF ==1 zsmax = ncread('xboutput.nc', 'zs_max'); zsmax = zsmax(:); %convert to column vector if numel(zsmax)> grids.nx zsmax2 = zsmax(end-grids.nx+1:end); else zsmax2 = zsmax; end else xbdata = xb_read_dat('zs_max.dat'); try zsmax(:,:) = xbdata.data(2).value(:,1,:); zsmax2 = zsmax'; zsmax2 = zsmax2(end-grids.nx+1:end); catch err clear zsmax2 zsmax2 = ones(size(zb2)).*tides.waterlevel(run_number); end end % size(zsmax2) zsmax2(zsmax2>999) = NaN; %sometimes has high output for last time step, so get rid of that ibad = find([zsmax2(:)-run.z(:)]< waves.XB.eps); zsmax2(ibad) = NaN; project.twl(run_number) = nanmax(zsmax2); if isnan(project.twl(run_number)) == 1 project.twl(run_number) = tides.waterlevel(run_number); end run.zsmax = zsmax2(:); %Use Runup Gauge Instead if project.XB.NetCDF ==1 zstemp = ncread('xboutput.nc', 'point_zs'); zstemp(zstemp>999) = NaN; project.twl(run_number) = nanmax(zstemp); if project.twl(run_number) == max(run.z) %dont use if matches dune crest elevation exactly for some reason, sometimes there are output issues project.twl(run_number) = tides.waterlevel(run_number); end end %keyname to end the while loop loop = 0; catch err count = count+1; pause(0.5); if count > 10 loop = 0; %get out of the loop if have tried too many times end end end end function setup_xbeach_grids(project, waves, grids, run, run_number) if run_number == 1 %write out files dlmwrite('x.grd', grids.XGrid(:), 'delimiter', ' ', 'precision', '%10.4f'); dlmwrite('y.grd', zeros(size(grids.XGrid(:))), 'delimiter', ' ', 'precision', '%10.4f'); end dlmwrite('z.dep', run.z(:), 'delimiter', ' ', 'precision', '%6.20f'); if run_number == 1 %not really a grid, but this needs to be written on first XBeach run, so better here than in the setup_hydro in case first run has too steep of a wave angle %set up a wave spectrum file. this never needs to get replaced but the spectra.spec file is changes each time fid = fopen([project.Directory, filesep, 'xbeach', filesep, 'specfilelist.txt'], 'w'); fprintf(fid, '%s\n', ['FILELIST']); fprintf(fid, '%s\n', [num2str(project.timeStep+project.XB.hydro_spinup),' ', num2str(waves.XB.dtbc),' spectra.spec']); fprintf(fid, '%s\n', [num2str(project.timeStep+project.XB.hydro_spinup),' ', num2str(waves.XB.dtbc),' spectra.spec']); fclose(fid); end end
github
ncohn/Windsurf-master
setproperty.m
.m
Windsurf-master/XBToolbox/setproperty.m
18,079
utf_8
1eb47d3ab29ecfd5684c11034b3265a4
function [OPT Set Default] = setproperty(OPT, inputCell, varargin) % SETPROPERTY generic routine to set values in PropertyName-PropertyValue pairs % % Routine to set properties based on PropertyName-PropertyValue % pairs (aka <keyword,value> pairs). Can be used in any function % where PropertyName-PropertyValue pairs are used. % % % [OPT Set Default] = setproperty(OPT, inputCell, varargin) % % input: % OPT = structure in which fieldnames are the keywords and the values % are the defaults % inputCell = must be a cell array containing single struct, or a set of % 'PropertyName', PropertyValue,... pairs. It is best practice % to pass the varargin of the calling function as the 2nd argument. % Property names must be strings. If they contain a dot (.) this is % interpreted a field separator. This can be used to assign % properties on a subfield level. % varargin = series of 'PropertyName', PropertyValue,... pairs to set % methods for setproperty itself. % % output: % OPT = structure, similar to the input argument OPT, with possibly % changed values in the fields % Set = structure, similar to OPT, values are true where OPT has been % set (and possibly changed) % Default = structure, similar to OPT, values are true where the values of % OPT are equal to the original OPT % % Example calls: % % [OPT Set Default] = setproperty(OPT, vararginOfCallingFunction) % [OPT Set Default] = setproperty(OPT, {'PropertyName', PropertyValue,...}) % [OPT Set Default] = setproperty(OPT, {OPT2}) % % Any number of leading structs with % any number of trailing <keyword,value> pairs: % [OPT Set Default] = setproperty(OPT1, OPT2, ..., OPTn) % [OPT Set Default] = setproperty(OPT1, OPT2, ..., OPTn,'PropertyName', PropertyValue,...) % % Different methods for dealing with class changes of variables, or % extra fields (properties that are not in the input structure) can % be defined as property-value pairs. Valid properties are % onExtraField and onClassChange: % % PROPERTY VALUE % onClassChange: ignore ignore (default) % warn throw warning % error throw error % onExtraField: silentIgnore silently ignore the field % warnIgnore ignore the field and throw warning % silentAppend silently append the field to OPT % warnAppend append the field to OPT and throw warning % error throw error (default) % % Example calls: % % [OPT Set Default] = setproperty(OPT, vararginOfCallingFunction,'onClassChange','warn') % [OPT Set Default] = setproperty(OPT, {'PropertyName', PropertyValue},'onExtraField','silentIgnore') % % % Example: % % +-------------------------------------------> % function y = dosomething(x,'debug',1) % OPT.debug = 0; % OPT = setproperty(OPT, varargin); % y = x.^2; % if OPT.debug; plot(x,y);pause; end % +-------------------------------------------> % % legacy syntax is also supported, but using legacy syntax prohibits the % setting of onClassChange and onExtraField methods: % % [OPT Set Default] = setproperty(OPT, varargin{:}) % OPT = setproperty(OPT, 'PropertyName', PropertyValue,...) % OPT = setproperty(OPT, OPT2) % % input: % OPT = structure in which fieldnames are the keywords and the values are the defaults % varargin = series of PropertyName-PropertyValue pairs to set % OPT2 = is a structure with the same fields as OPT. % % Internally setproperty translates OPT2 into a set of % PropertyName-PropertyValue pairs (see example below) as in: % OPT2 = struct( 'propertyName1', 1,... % 'propertyName2', 2); % varcell = reshape([fieldnames(OPT2)'; struct2cell(OPT2)'], 1, 2*length(fieldnames(OPT2))); % OPT = setproperty(OPT, varcell{:}); % % Change log: % 2011-09-30: full code rewrite to include: % - setpropertyInDeeperStruct functionality % - user defined handling of extra fields % - class change warning/error message % % See also: VARARGIN, STRUCT, MERGESTRUCTS %% Copyright notice % -------------------------------------------------------------------- % Copyright (C) 2009 Delft University of Technology % C.(Kees) den Heijer % % [email protected] % % Faculty of Civil Engineering and Geosciences % P.O. Box 5048 % 2600 GA Delft % The Netherlands % % This library is free software; you can redistribute it and/or % modify it under the terms of the GNU Lesser General Public % License as published by the Free Software Foundation; either % version 2.1 of the License, or (at your option) any later version. % % This library is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % Lesser General Public License for more details. % % You should have received a copy of the GNU Lesser General Public % License along with this library; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 % USA % or http://www.gnu.org/licenses/licenses.html, http://www.gnu.org/, http://www.fsf.org/ % -------------------------------------------------------------------- % This tools is part of <a href="http://OpenEarth.Deltares.nl">OpenEarthTools</a>. % OpenEarthTools is an online collaboration to share and manage data and % programming tools in an open source, version controlled environment. % Sign up to recieve regular updates of this function, and to contribute % your own tools. %% Version <http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html> % Created: 26 Feb 2009 % Created with Matlab version: 7.4.0.287 (R2007a) % $Id: setproperty.m 7878 2013-01-07 12:53:40Z boer_g $ % $Date: 2013-01-07 13:53:40 +0100 (Mon, 07 Jan 2013) $ % $Author: boer_g $ % $Revision: 7878 $ % $HeadURL: https://svn.oss.deltares.nl/repos/openearthtools/trunk/matlab/setproperty.m $ % $Keywords: $ %% shortcut function if there is nothing to set (1) if nargin==1||isempty(inputCell) if nargout > 1 % process Set flds1 = fieldnames(OPT); Set = [flds1,repmat({false},size(flds1))]'; Set = struct(Set{:}); end if nargout > 2 % process Default Default = [flds1,repmat({true},size(flds1))]'; Default = struct(Default{:}); end return end %% check and parse inputCell (usually the varargin struct in the calling function) % determine mode from class of the second argument switch(class(inputCell)) case 'struct' % recursively let setproperty peel all leading structs % with optional trailing keyword,value> pairs inputCell = setproperty(inputCell,varargin{:}); inputCell = struct2arg(inputCell); varargin = {}; case 'char' % legay syntax mode inputCell = [{inputCell} varargin]; varargin = {}; case 'cell' % new syntax mode, do nothing otherwise error('SETPROPERTY:inputCell',... 'Second input must be a cell, (or a char or struct for legacy syntax)') end %% shortcut function if there is nothing to set (2) if numel(inputCell) == 1 && isempty(inputCell{1}) if nargout > 1 % process Set flds1 = fieldnames(OPT); Set = [flds1,repmat({false},size(flds1))]'; Set = struct(Set{:}); end if nargout > 2 % process Default Default = [flds1,repmat({true},size(flds1))]'; Default = struct(Default{:}); end return end if odd(length(inputCell)) %then length must be 1 if length(inputCell) == 1 %then the inputCell must be a structure if ~isstruct(inputCell{1}) error('SETPROPERTY:inputCell',... 'Second argument inputCell must be a cell containing a single struct or property/value pairs') end flds2 = fieldnames(inputCell{1})'; newVal = struct2cell(inputCell{1})'; else error('SETPROPERTY:inputCell',... 'Second argument inputCell must be a cell containing a single struct or property/value pairs') end else flds2 = inputCell(1:2:end); if ~all(cellfun(@ischar,flds2)) error('SETPROPERTY:inputCell',... 'Second argument inputCell, property names should be strings') end newVal = inputCell(2:2:end); end %% check and parse varargin error(nargchk(0, 4, length(varargin), 'struct')) if odd(length(varargin)) error('SETPROPERTY:varargin',... 'Set onClassChange and onExtraField with the varargin, as keyword value pairs'); end onExtraField = 'error'; onClassChange = 'ignore'; if ~isempty(varargin) for ii = 1:2:length(varargin) switch varargin{ii} case 'onClassChange' if ischar(varargin{ii+1}) && ismember(varargin(ii+1),... {'ignore','warn','error'}) onClassChange = varargin{ii+1}; else error('SETPROPERTY:InvalidMethod',... 'Valid methods for onClassChange are: ignore, warn and error'); end case 'onExtraField' if ischar(varargin{ii+1}) && ismember(varargin(ii+1),... {'silentAppend','warnAppend','silentIgnore','warnIgnore','error'}) onExtraField = varargin{ii+1}; else error('SETPROPERTY:InvalidMethod',... 'Valid methods for onExtraField are: append, silentIgnore, warnIgnore, error'); end otherwise error('SETPROPERTY:InvalidKeyword', ... 'Supported keywords are onClassChange and onExtraField'); end end end switch onClassChange case 'warn' warnOnClassChange = true; errorOnClassChange = false; case 'error' warnOnClassChange = false; errorOnClassChange = true; case 'ignore' warnOnClassChange = false; errorOnClassChange = false; end %% copy the original OPT only if Default has to be returned if nargout > 2 OPToriginal = OPT; end %% check field names, and distinguish between field to set and extra fields % flds1 contains field names of OPT flds1 = fieldnames(OPT); % fldsCell contains field names to assign, split per subfield fldsCell = regexp(flds2,'[^\.]*','match'); fldsCellLen = cellfun(@length,fldsCell); % check if all field names are valid to assign allFieldNames = [fldsCell{:}]; validFieldName = cellfun(@(x) (isvarname(x) | iskeyword(x)),allFieldNames); % a field like 'case' is allowed also, but is not a valid varname if ~all(validFieldName) error('SETPROPERTY:invalidFieldName',... '\nThe following field name is not valid: %s',allFieldNames{~validFieldName}); end % identify fldsToSet for simple field names (without subfields) % fldsToSet = ismember(flds2,flds1); % As ismember is rather slow, this is replaced by more optimized code fldsToSet = false(size(flds2)); for ii = find(fldsCellLen==1) fldsToSet(ii) = any(strcmp(flds2(ii),flds1)); end % identify fldsToSet for field names with subfields) for ii = find(fldsCellLen>1) fldsToSet(ii) = isfield2(OPT,fldsCell{ii}); end % all other fields are either to be set, or extra fldsExtra = ~fldsToSet; %% process fldsToSet if any(fldsToSet) for ii = find(fldsToSet) switch length(fldsCell{ii}) case 1 if warnOnClassChange || errorOnClassChange class1 = class(OPT.(fldsCell{ii}{1})); class2 = class(newVal{ii}); classChange(flds2{ii},class1,class2,warnOnClassChange,errorOnClassChange); end OPT.(fldsCell{ii}{1}) = newVal{ii}; case 2 if warnOnClassChange || errorOnClassChange class1 = class(OPT.(fldsCell{ii}{1}).(fldsCell{ii}{2})); class2 = class(newVal{ii}); classChange(flds2{ii},class1,class2,warnOnClassChange,errorOnClassChange); end OPT.(fldsCell{ii}{1}).(fldsCell{ii}{2}) = newVal{ii}; otherwise if warnOnClassChange || errorOnClassChange class1 = class(getfield(OPT,fldsCell{ii}{:})); class2 = class(newVal{ii}); classChange(flds2{ii},class1,class2,warnOnClassChange,errorOnClassChange); end OPT = setfield(OPT,fldsCell{ii}{:},newVal{ii}); end end end %% deal with fldsExtra if any(fldsExtra) switch lower(onExtraField) case {'silentappend','warnappend'} % append extra fields to OPT for ii = find(fldsExtra) switch length(fldsCell{ii}) case 1 OPT.(flds2{ii}) = newVal{ii}; otherwise OPT = setfield(OPT,fldsCell{ii}{:},newVal{ii}); end end if strcmpi(onExtraField,'warnAppend') % throw a warning warning('SETPROPERTY:ExtraField',... '\nThe following field is Extra and appended to OPT: %s',flds2{fldsExtra}); end case 'silentignore' % do nothing, silently ignore extra fields case 'warnignore' warning('SETPROPERTY:ExtraField',... '\nThe following field is Extra and thus ignored: %s',flds2{fldsExtra}); case 'error' error('SETPROPERTY:ExtraField',... '\nThe following field is Extra: %s',flds2{fldsExtra}); end end %% assign Output if nargout > 1 % process Set Set = [flds1,repmat({false},size(flds1))]'; Set = struct(Set{:}); if any(fldsToSet) for ii = find(fldsToSet) switch length(fldsCell{ii}) case 1 Set.(fldsCell{ii}{1}) = true; otherwise % this routine is rather slow, would be nice to add case 2 to cover the most common calls for nn = 1:length(fldsCell{ii})-1 if ~isstruct(getfield(Set,fldsCell{ii}{1:nn})) %#ok<*GFLD> substruct = [fieldnames(getfield(OPT,fldsCell{ii}{1:nn})),... repmat({false},size(fieldnames(getfield(OPT,fldsCell{ii}{1:nn}))))]'; Set = setfield(Set,fldsCell{ii}{1:nn},[]); %#ok<*SFLD> Set = setfield(Set,fldsCell{ii}{1:nn},struct(substruct{:})); end end Set = setfield(Set,fldsCell{ii}{:},true); end end end if any(fldsExtra) switch lower(onExtraField) case {'silentappend','warnappend'} for ii = find(fldsExtra) switch length(fldsCell{ii}) case 1 Set.(flds2{ii}) = true; otherwise Set = setfield(Set,fldsCell{ii}{:},true); end end end end end if nargout > 2 % process Default Default = [flds1,repmat({true},size(flds1))]'; Default = struct(Default{:}); if any(fldsToSet) for ii = find(fldsToSet) switch length(fldsCell{ii}) case 1 Default.(fldsCell{ii}{1}) = ... isequalwithequalnans(OPToriginal.(fldsCell{ii}{1}),OPT.(fldsCell{ii}{1})); otherwise % this routine is rather slow, would be nice to add case 2 to cover the most common calls for nn = 1:length(fldsCell{ii})-1 if ~isstruct(getfield(Default,fldsCell{ii}{1:nn})) %#ok<*GFLD> substruct = [fieldnames(getfield(OPT,fldsCell{ii}{1:nn})),... repmat({true},size(fieldnames(getfield(OPT,fldsCell{ii}{1:nn}))))]'; Default = setfield(Default,fldsCell{ii}{1:nn},[]); %#ok<*SFLD> Default = setfield(Default,fldsCell{ii}{1:nn},struct(substruct{:})); end end Default = setfield(Default,fldsCell{ii}{:},... isequalwithequalnans(getfield(OPToriginal,fldsCell{ii}{:}),getfield(OPT,fldsCell{ii}{:}))); end end end if any(fldsExtra) switch lower(onExtraField) case {'silentappend','warnappend'} for ii = find(fldsExtra) switch length(fldsCell{ii}) case 1 Default.(flds2{ii}) = false; otherwise Default = setfield(Default,fldsCell{ii}{:},false); end end end end end function tf = isfield2(OPT,fldsCell) if isfield(OPT,fldsCell{1}) if length(fldsCell) > 1 tf = isfield2(OPT.(fldsCell{1}),fldsCell(2:end)); else tf = true; end else tf = false; end function classChange(fld,class1,class2,warnOnClassChange,errorOnClassChange) if ~strcmp(class1,class2) if warnOnClassChange warning('SETPROPERTY:ClassChange', ... 'Class change of field ''%s'' from %s to %s',... fld,class1,class2); elseif errorOnClassChange error('SETPROPERTY:ClassChange', ... 'Class change of field ''%s'' from %s to %s not allowed',... fld,class1,class2); end end function out = odd(in) %ODD test whether number if odd out = mod(in,2)==1; %% EOF
github
ncohn/Windsurf-master
cdm_params.m
.m
Windsurf-master/SubRoutines/cdm_params.m
4,220
utf_8
ae97a11957e28f0ecc308fa05be70f86
%cdm_params.m - Code to set up Coastal Dune Model (CDM) parameter file for Windsurf coupler %Created By: N. Cohn, Oregon State University function cdm_params(project, grid, veg, sed, idx, winds) %open file fid = fopen([project.Directory, filesep, 'cdm', filesep, 'cdm.par'], 'w'); %write out parameters fprintf(fid, '%s\n', ['NX = ', num2str(grid.nx)]); fprintf(fid, '%s\n', ['NY = ', num2str(grid.ny)]); fprintf(fid, '%s\n', ['dx = ', num2str(grid.dx/cosd(winds.winddir(idx)))]); fprintf(fid, '%s\n', ['dt_max = ', num2str(project.CDM.timestep)]); if project.flag.CDM ~=2 fprintf(fid, '%s\n', ['Nt = ', num2str(project.timeStep/(project.CDM.timestep))]); fprintf(fid, '%s\n', ['save.every = ', num2str(project.timeStep/(project.CDM.timestep))]); else %only need to run 1 time step if just want wind field fprintf(fid, '%s\n', ['Nt = 1']); fprintf(fid, '%s\n', ['save.every = 1']); end fprintf(fid, '%s\n', ['Nt0 = 0']); fprintf(fid, '%s\n', ['save.x-line = 0']); fprintf(fid, '%s\n', ['save.dir = ./CDM_temp']); fprintf(fid, '%s\n', ['calc.x_periodic = 0']); fprintf(fid, '%s\n', ['calc.y_periodic = 0']); fprintf(fid, '%s\n', ['calc.shift_back = 0']); fprintf(fid, '%s\n', ['influx = const']); fprintf(fid, '%s\n', ['q_in = 0']); %since the new model should inherintly add in the q_in term we leave this as zero for the time being fprintf(fid, '%s\n', ['wind = const']); fprintf(fid, '%s\n', ['constwind.u = ', num2str(winds.windshear(idx))]); fprintf(fid, '%s\n', ['constwind.direction = 0']); %this doesnt actually work - CDM can currently only simulate cross-shore winds fprintf(fid, '%s\n', ['wind.fraction = 1']); fprintf(fid, '%s\n', ['veget.calc = 1']); if project.flag.VegCode==1 fprintf(fid, '%s\n', ['veget.xmin = 0']); else fprintf(fid, '%s\n', ['veget.xmin = ', num2str(veg.CDM.xmin)]); end fprintf(fid, '%s\n', ['veget.zmin = ', num2str(veg.CDM.elevMin)]); fprintf(fid, '%s\n', ['veget.Tveg = ', num2str(veg.CDM.Tveg)]); fprintf(fid, '%s\n', ['veget.sigma = ', num2str(veg.CDM.sigma)]); fprintf(fid, '%s\n', ['veget.beta = ', num2str(veg.CDM.beta)]); fprintf(fid, '%s\n', ['veget.m = ', num2str(veg.CDM.m)]); fprintf(fid, '%s\n', ['veget.season.t = 0']); fprintf(fid, '%s\n', ['veget.Vlateral.factor = 0']); fprintf(fid, '%s\n', ['calc.shore = 0']); fprintf(fid, '%s\n', ['beach.tau_t_L = 0.5']); fprintf(fid, '%s\n', ['shore.MHWL = 0']); fprintf(fid, '%s\n', ['shore.sealevel = 0']); fprintf(fid, '%s\n', ['shore.motion = 0']); fprintf(fid, '%s\n', ['shore.sealevelrise = 0']); fprintf(fid, '%s\n', ['shore.alongshore_grad = 0']); fprintf(fid, '%s\n', ['calc.storm = 0']); fprintf(fid, '%s\n', ['shore.correct.profile = 0']); fprintf(fid, '%s\n', ['init_h.x-line = 0']); fprintf(fid, '%s\n', ['veget.Init-Surf = init_h']); fprintf(fid, '%s\n', ['veget.init_h.file = init_vx.dat']); fprintf(fid, '%s\n', ['veget.init_h.file_aux = init_vy.dat']); fprintf(fid, '%s\n', ['veget.rho.max = ', num2str(veg.CDM.maximumDensity)]); fprintf(fid, '%s\n', ['salt.d = ', num2str(sed.CDM.D)]); %grain size in meters %set up grids fprintf(fid, '%s\n', ['Init-Surf = init_h']); fprintf(fid, '%s\n', ['init_h.file= init_h.dat']); %fprintf(fid, '%s\n', ['nonerod.Init-Surf = init_h']); fprintf(fid, '%s\n', ['nonerod.init_h.file = init_h_nonerod.dat']); %Save Outputs - 0 = save, 1 = don't save fprintf(fid, '%s\n', ['dontsave.veget = 0']); fprintf(fid, '%s\n', ['dontsave.u = 0']); fprintf(fid, '%s\n', ['dontsave.flux = 1']); fprintf(fid, '%s\n', ['dontsave.flux_s = 1']); fprintf(fid, '%s\n', ['dontsave.shear = 0']); fprintf(fid, '%s\n', ['dontsave.shear_pert = 0']); fprintf(fid, '%s\n', ['dontsave.stall = 0']); fprintf(fid, '%s\n', ['dontsave.rho = 1']); fprintf(fid, '%s\n', ['dontsave.h_deposit = 1']); fprintf(fid, '%s\n', ['dontsave.h_nonerod = 1']); fprintf(fid, '%s\n', ['dontsave.h_sep = 0']); fprintf(fid, '%s\n', ['dontsave.dhdt = 1']); fclose(fid); end
github
ncohn/Windsurf-master
progressbar.m
.m
Windsurf-master/SubRoutines/progressbar.m
11,767
utf_8
06705e480618e134da62478338e8251c
function progressbar(varargin) % Description: % progressbar() provides an indication of the progress of some task using % graphics and text. Calling progressbar repeatedly will update the figure and % automatically estimate the amount of time remaining. % This implementation of progressbar is intended to be extremely simple to use % while providing a high quality user experience. % % Features: % - Can add progressbar to existing m-files with a single line of code. % - Supports multiple bars in one figure to show progress of nested loops. % - Optional labels on bars. % - Figure closes automatically when task is complete. % - Only one figure can exist so old figures don't clutter the desktop. % - Remaining time estimate is accurate even if the figure gets closed. % - Minimal execution time. Won't slow down code. % - Randomized color. When a programmer gets bored... % % Example Function Calls For Single Bar Usage: % progressbar % Initialize/reset % progressbar(0) % Initialize/reset % progressbar('Label') % Initialize/reset and label the bar % progressbar(0.5) % Update % progressbar(1) % Close % % Example Function Calls For Multi Bar Usage: % progressbar(0, 0) % Initialize/reset two bars % progressbar('A', '') % Initialize/reset two bars with one label % progressbar('', 'B') % Initialize/reset two bars with one label % progressbar('A', 'B') % Initialize/reset two bars with two labels % progressbar(0.3) % Update 1st bar % progressbar(0.3, []) % Update 1st bar % progressbar([], 0.3) % Update 2nd bar % progressbar(0.7, 0.9) % Update both bars % progressbar(1) % Close % progressbar(1, []) % Close % progressbar(1, 0.4) % Close % % Notes: % For best results, call progressbar with all zero (or all string) inputs % before any processing. This sets the proper starting time reference to % calculate time remaining. % Bar color is choosen randomly when the figure is created or reset. Clicking % the bar will cause a random color change. % % Demos: % % Single bar % m = 500; % progressbar % Init single bar % for i = 1:m % pause(0.01) % Do something important % progressbar(i/m) % Update progress bar % end % % % Simple multi bar (update one bar at a time) % m = 4; % n = 3; % p = 100; % progressbar(0,0,0) % Init 3 bars % for i = 1:m % progressbar([],0) % Reset 2nd bar % for j = 1:n % progressbar([],[],0) % Reset 3rd bar % for k = 1:p % pause(0.01) % Do something important % progressbar([],[],k/p) % Update 3rd bar % end % progressbar([],j/n) % Update 2nd bar % end % progressbar(i/m) % Update 1st bar % end % % % Fancy multi bar (use labels and update all bars at once) % m = 4; % n = 3; % p = 100; % progressbar('Monte Carlo Trials','Simulation','Component') % Init 3 bars % for i = 1:m % for j = 1:n % for k = 1:p % pause(0.01) % Do something important % % Update all bars % frac3 = k/p; % frac2 = ((j-1) + frac3) / n; % frac1 = ((i-1) + frac2) / m; % progressbar(frac1, frac2, frac3) % end % end % end % % Author: % Steve Hoelzer % % Revisions: % 2002-Feb-27 Created function % 2002-Mar-19 Updated title text order % 2002-Apr-11 Use floor instead of round for percentdone % 2002-Jun-06 Updated for speed using patch (Thanks to waitbar.m) % 2002-Jun-19 Choose random patch color when a new figure is created % 2002-Jun-24 Click on bar or axes to choose new random color % 2002-Jun-27 Calc time left, reset progress bar when fractiondone == 0 % 2002-Jun-28 Remove extraText var, add position var % 2002-Jul-18 fractiondone input is optional % 2002-Jul-19 Allow position to specify screen coordinates % 2002-Jul-22 Clear vars used in color change callback routine % 2002-Jul-29 Position input is always specified in pixels % 2002-Sep-09 Change order of title bar text % 2003-Jun-13 Change 'min' to 'm' because of built in function 'min' % 2003-Sep-08 Use callback for changing color instead of string % 2003-Sep-10 Use persistent vars for speed, modify titlebarstr % 2003-Sep-25 Correct titlebarstr for 0% case % 2003-Nov-25 Clear all persistent vars when percentdone = 100 % 2004-Jan-22 Cleaner reset process, don't create figure if percentdone = 100 % 2004-Jan-27 Handle incorrect position input % 2004-Feb-16 Minimum time interval between updates % 2004-Apr-01 Cleaner process of enforcing minimum time interval % 2004-Oct-08 Seperate function for timeleftstr, expand to include days % 2004-Oct-20 Efficient if-else structure for sec2timestr % 2006-Sep-11 Width is a multiple of height (don't stretch on widescreens) % 2010-Sep-21 Major overhaul to support multiple bars and add labels % persistent progfig progdata lastupdate % Get inputs if nargin > 0 input = varargin; ninput = nargin; else % If no inputs, init with a single bar input = {0}; ninput = 1; end % If task completed, close figure and clear vars, then exit if input{1} == 1 if ishandle(progfig) delete(progfig) % Close progress bar end clear progfig progdata lastupdate % Clear persistent vars drawnow return end % Init reset flag resetflag = false; % Set reset flag if first input is a string if ischar(input{1}) resetflag = true; end % Set reset flag if all inputs are zero if input{1} == 0 % If the quick check above passes, need to check all inputs if all([input{:}] == 0) && (length([input{:}]) == ninput) resetflag = true; end end % Set reset flag if more inputs than bars if ninput > length(progdata) resetflag = true; end % If reset needed, close figure and forget old data if resetflag if ishandle(progfig) delete(progfig) % Close progress bar end progfig = []; progdata = []; % Forget obsolete data end % Create new progress bar if needed if ishandle(progfig) else % This strange if-else works when progfig is empty (~ishandle() does not) % Define figure size and axes padding for the single bar case height = 0.03; width = height * 8; hpad = 0.02; vpad = 0.25; % Figure out how many bars to draw nbars = max(ninput, length(progdata)); % Adjust figure size and axes padding for number of bars heightfactor = (1 - vpad) * nbars + vpad; height = height * heightfactor; vpad = vpad / heightfactor; % Initialize progress bar figure left = (1 - width) / 2; bottom = (1 - height) / 2; progfig = figure(... 'Units', 'normalized',... 'Position', [left bottom width height],... 'NumberTitle', 'off',... 'Resize', 'off',... 'MenuBar', 'none' ); % Initialize axes, patch, and text for each bar left = hpad; width = 1 - 2*hpad; vpadtotal = vpad * (nbars + 1); height = (1 - vpadtotal) / nbars; for ndx = 1:nbars % Create axes, patch, and text bottom = vpad + (vpad + height) * (nbars - ndx); progdata(ndx).progaxes = axes( ... 'Position', [left bottom width height], ... 'XLim', [0 1], ... 'YLim', [0 1], ... 'Box', 'on', ... 'ytick', [], ... 'xtick', [] ); progdata(ndx).progpatch = patch( ... 'XData', [0 0 0 0], ... 'YData', [0 0 1 1] ); progdata(ndx).progtext = text(0.99, 0.5, '', ... 'HorizontalAlignment', 'Right', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); progdata(ndx).proglabel = text(0.01, 0.5, '', ... 'HorizontalAlignment', 'Left', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); if ischar(input{ndx}) set(progdata(ndx).proglabel, 'String', input{ndx}) input{ndx} = 0; end % Set callbacks to change color on mouse click set(progdata(ndx).progaxes, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progpatch, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progtext, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).proglabel, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) % Pick a random color for this patch changecolor([], [], progdata(ndx).progpatch) % Set starting time reference if ~isfield(progdata(ndx), 'starttime') || isempty(progdata(ndx).starttime) progdata(ndx).starttime = clock; end end % Set time of last update to ensure a redraw lastupdate = clock - 1; end % Process inputs and update state of progdata for ndx = 1:ninput if ~isempty(input{ndx}) progdata(ndx).fractiondone = input{ndx}; progdata(ndx).clock = clock; end end % Enforce a minimum time interval between graphics updates myclock = clock; if abs(myclock(6) - lastupdate(6)) < 0.01 % Could use etime() but this is faster return end % Update progress patch for ndx = 1:length(progdata) set(progdata(ndx).progpatch, 'XData', ... [0, progdata(ndx).fractiondone, progdata(ndx).fractiondone, 0]) end % Update progress text if there is more than one bar if length(progdata) > 1 for ndx = 1:length(progdata) set(progdata(ndx).progtext, 'String', ... sprintf('%1d%%', floor(100*progdata(ndx).fractiondone))) end end % Update progress figure title bar if progdata(1).fractiondone > 0 runtime = etime(progdata(1).clock, progdata(1).starttime); timeleft = runtime / progdata(1).fractiondone - runtime; timeleftstr = sec2timestr(timeleft); titlebarstr = sprintf('%2d%% %s remaining', ... floor(100*progdata(1).fractiondone), timeleftstr); else titlebarstr = ' 0%'; end set(progfig, 'Name', titlebarstr) % Force redraw to show changes drawnow % Record time of this update lastupdate = clock; % ------------------------------------------------------------------------------ function changecolor(h, e, progpatch) %#ok<INUSL> % Change the color of the progress bar patch % Prevent color from being too dark or too light colormin = 1.5; colormax = 2.8; thiscolor = rand(1, 3); while (sum(thiscolor) < colormin) || (sum(thiscolor) > colormax) thiscolor = rand(1, 3); end set(progpatch, 'FaceColor', thiscolor) % ------------------------------------------------------------------------------ function timestr = sec2timestr(sec) % Convert a time measurement from seconds into a human readable string. % Convert seconds to other units w = floor(sec/604800); % Weeks sec = sec - w*604800; d = floor(sec/86400); % Days sec = sec - d*86400; h = floor(sec/3600); % Hours sec = sec - h*3600; m = floor(sec/60); % Minutes sec = sec - m*60; s = floor(sec); % Seconds % Create time string if w > 0 if w > 9 timestr = sprintf('%d week', w); else timestr = sprintf('%d week, %d day', w, d); end elseif d > 0 if d > 9 timestr = sprintf('%d day', d); else timestr = sprintf('%d day, %d hr', d, h); end elseif h > 0 if h > 9 timestr = sprintf('%d hr', h); else timestr = sprintf('%d hr, %d min', h, m); end elseif m > 0 if m > 9 timestr = sprintf('%d min', m); else timestr = sprintf('%d min, %d sec', m, s); end else timestr = sprintf('%d sec', s); end
github
ncohn/Windsurf-master
xb_params.m
.m
Windsurf-master/SubRoutines/xb_params.m
17,952
utf_8
85769a1f7fe0b8001213ba7691c57bf3
%xb_params.m - This code ssets up XBeach params file for Windsurf %Created By: N. Cohn, Oregon State University function xb_params(project, grid, waves, flow, tides, winds, sed, veg, run_number) %open filename fid = fopen(['params.txt'], 'w'); fprintf(fid, '%s\n', 'left = 0'); fprintf(fid, '%s\n', 'right = 0'); %determine if 1D or 2D grid if waves.XB.nonhydrostatic ~= 1 fprintf(fid, '%s\n', 'back = abs_1d'); fprintf(fid, '%s\n', 'front = abs_1d'); end %NECESSARY VARIABLES %Model Setup fprintf(fid, '%s\n', 'depfile = z.dep'); fprintf(fid, '%s\n', 'xfile = x.grd'); fprintf(fid, '%s\n', 'yfile = y.grd'); fprintf(fid, '%s\n', ['nx = ', num2str(grid.nx-1)]); fprintf(fid, '%s\n', ['ny = 0']); fprintf(fid, '%s\n', 'vardx = 1'); fprintf(fid, '%s\n', 'posdwn = -1'); %Waves/Flow fprintf(fid, '%s\n', 'lwave = 1'); fprintf(fid, '%s\n', ['dtheta = ', num2str(waves.XB.dtheta)]); fprintf(fid, '%s\n', ['thetamin = ', num2str(waves.XB.thetamin)]); fprintf(fid, '%s\n', ['thetamax = ', num2str(waves.XB.thetamax)]); fprintf(fid, '%s\n', ['random = ', num2str(waves.XB.random)]); fprintf(fid, '%s\n', ['eps = ', num2str(waves.XB.eps)]); %threshold depth for drying and flooding if waves.XB.dtheta < 359 fprintf(fid, '%s\n', 'single_dir = 1'); %try new key name for single wave direction end fprintf(fid, '%s\n', ['fw = ',num2str(waves.XB.fw)]); % if regimes.wave_type(run_number) == 1 %instationary wave solver (jonswap) fprintf(fid, '%s\n', ['instat = 4']); fprintf(fid, '%s\n', ['bcfile = specfilelist.txt']); % elseif regimes.wave_type(run_number) == 5 %external spectral input % fprintf(fid, '%s\n', ['instat = swan']); % xb_external_wave_spectrum(waves.XB.spectraFilename, project.startTime+project.Times_days(run_number)) % fprintf(fid, '%s\n', ['dthetaS_XB = ', num2str(waves.XB.dthetaS_XB)]); %have to do this because SWAN was assumed cartesian and xbeach expects nautical convention, not sure this should always be zero - should recheck? % fprintf(fid, '%s\n', ['bcfile = specfilelist.txt']); % elseif waves.XB.nonhydrostatic ~= 1 %if stationary wave case % % fprintf(fid, '%WaveRs\n', ['wbctype = stat']); % fprintf(fid, '%s\n', ['instat = 0']); % fprintf(fid, '%s\n', ['bcfile = specfilelist.txt']); % end if waves.XB.nonhydrostatic == 1 %add the non-hydrostatic correction if needed. should only not do if running stationary waves fprintf(fid, '%s\n', ['nonh = 1']); end if sed.XB.lws == 1 || waves.XB.nonhydrostatic == 1 fprintf(fid, '%s\n', ['lws = 1']); else fprintf(fid, '%s\n', 'lws =0'); end if sed.XB.lwt == 1 || waves.XB.nonhydrostatic == 1 fprintf(fid, '%s\n', ['lwt = 1']); else fprintf(fid, '%s\n', 'lwt =0'); end %Sediment and Morphology fprintf(fid, '%s\n', ['sedcal = ', num2str(sed.XB.sedcal)]); fprintf(fid, '%s\n', ['morphology = ', num2str(sed.XB.morphology)]); if sed.XB.morphology == 1 fprintf(fid, '%s\n', ['morstart = ', num2str(project.XB.hydro_spinup)]); fprintf(fid, '%s\n', 'sedtrans = 1'); else fprintf(fid, '%s\n', 'sedtrans = 0'); %dont bother with sed transport calcs if dont need them end fprintf(fid, '%s\n', ['morfac = ', num2str(sed.XB.morfac)]); %fprintf(fid, '%s\n', ['morfacopt = ' num2str(sed.XB.morfacopt)]); fprintf(fid, '%s\n', ['morfacopt = 1']); if waves.XB.nonhydrostatic == 1 %nonhydrostatic automatically accounts for assymmetry and skewness, so dont need to include variables %if running a version of xbeach that has nielsen-bagnold formula %included can run the following - only use if using the wave %resolving form of the model if sed.XB.form == 3 %add these additional values for now, other default values chosen by model are probably OK fprintf(fid, '%s\n', ['form = nielsen_bagnold']); %this is a custom version of sed transport equations that is not in all versions of XBeach fprintf(fid, '%s\n', ['fricAd = 1']); fprintf(fid, '%s\n', ['fric89 = 1']); % fprintf(fid, '%s\n', ['turbadv = 1']); fprintf(fid, '%s\n', ['Tm0=', num2str(waves.Tp(run_number))]); elseif sed.XB.form == 1 fprintf(fid, '%s\n', ['form = soulsby_vanrijn']); else fprintf(fid, '%s\n', ['form = vanthiel_vanrijn']); end else fprintf(fid, '%s\n', ['facAs = ', num2str(sed.XB.facAs)]); fprintf(fid, '%s\n', ['facSk = ', num2str(sed.XB.facSk)]); if sed.XB.form == 3 %shouldnt use nielsen bagnold if using hydrostatic model, so default to other formulation fprintf(fid, '%s\n', ['form = soulsby_vanrijn']); elseif sed.XB.form == 1 fprintf(fid, '%s\n', ['form = soulsby_vanrijn']); else fprintf(fid, '%s\n', ['form = vanthiel_vanrijn']); end end if sed.XB.avalanche == 1 fprintf(fid, '%s\n', ['avalanching = ', num2str(sed.XB.avalanche)]); fprintf(fid, '%s\n', ['wetslp = ', num2str(sed.XB.wetslope)]); fprintf(fid, '%s\n', ['dryslp = ', num2str(sed.XB.dryslope)]); else fprintf(fid, '%s\n', ['avalanching = 0']); end %Other Input types fprintf(fid, '%s\n', 'zs0file = waterlevel.inp'); fprintf(fid, '%s\n', 'tideloc = 1'); %Currently leave winds out of XBeach - not necessary for this application %fprintf(fid, '%s\n', 'windfile = winds.inp'); %Currently structures not yet implemented %if structures.struct == 1 % fprintf(fid, '%s\n', 'struct = 1'); % fprintf(fid, '%s\n', 'ne_layer = ne_layer.grd'); %end %Output Requests % if sed.XB.morfacopt == 1 fprintf(fid, '%s\n', ['tstart = ', num2str(project.XB.hydro_spinup)]); fprintf(fid, '%s\n', ['tstop = ', num2str(project.timeStep+project.XB.hydro_spinup)]); fprintf(fid, '%s\n', ['tint = ', num2str(project.timeStep-1)]); %time step for output is calculated just as from tstart fprintf(fid, '%s\n', ['tintg = ', num2str(project.timeStep-1)]); %time step for output is calculated just as from tstart fprintf(fid, '%s\n', ['tintm = ', num2str(project.timeStep)]); %time step for output is calculated just as from tstart % elseif sed.XB.morfacopt == 0 % timeStep = project.timeStep/regimes.morfac(run_number); % fprintf(fid, '%s\n', ['tstart = ', num2str(project.XB.hydro_spinup)]); % fprintf(fid, '%s\n', ['tstop = ', num2str(timeStep+project.XB.hydro_spinup)]); % fprintf(fid, '%s\n', ['tint = ', num2str(timeStep-1)]); %time step for output is calculated just as from tstart % fprintf(fid, '%s\n', ['tintg = ', num2str(timeStep-1)]); %time step for output is calculated just as from tstart % fprintf(fid, '%s\n', ['tintm = ', num2str(timeStep)]); %time step for output is calculated just as from tstart % % end if project.XB.outputType == -1 fprintf(fid, '%s\n', 'nglobalvar = -1'); elseif project.XB.outputType == 0 fprintf(fid, '%s\n', 'nglobalvar = 1'); %fprintf(fid, '%s\n', 'H'); %fprintf(fid, '%s\n', 'zs'); fprintf(fid, '%s\n', 'zb'); %fprintf(fid, '%s\n', 'cctot'); fprintf(fid, '%s\n', 'nmeanvar = 2'); fprintf(fid, '%s\n', 'H'); fprintf(fid, '%s\n', 'zs'); % fprintf(fid, '%s\n', 'cctot'); %fprintf(fid, '%s\n', 'ccg'); fprintf(fid, '%s\n', 'nrugauge = 1'); fprintf(fid, '%s\n', [num2str(nanmean(grid.XGrid)) , ' 0 runuptrans']); fprintf(fid, '%s\n', ['rugdepth = ', num2str(waves.XB.eps)]); fprintf(fid, '%s\n', 'tintp = 5'); %save runup output every 5 second (maybe too much for long sims?) elseif project.XB.outputType == 1 fprintf(fid, '%s\n', 'nglobalvar = 4'); fprintf(fid, '%s\n', 'H'); fprintf(fid, '%s\n', 'zs'); fprintf(fid, '%s\n', 'u'); fprintf(fid, '%s\n', 'v'); elseif project.XB.outputType == 2 fprintf(fid, '%s\n', 'nglobalvar = 5'); fprintf(fid, '%s\n', 'H'); fprintf(fid, '%s\n', 'zs'); fprintf(fid, '%s\n', 'u'); fprintf(fid, '%s\n', 'v'); fprintf(fid, '%s\n', 'zb'); elseif project.XB.outputType == 3 fprintf(fid, '%s\n', 'nglobalvar = 10'); fprintf(fid, '%s\n', 'H'); fprintf(fid, '%s\n', 'zb'); fprintf(fid, '%s\n', 'dxbdx'); fprintf(fid, '%s\n', 'dzbdy'); fprintf(fid, '%s\n', 'dzbdt'); fprintf(fid, '%s\n', 'sedero'); fprintf(fid, '%s\n', 'ccg'); fprintf(fid, '%s\n', 'ccbg'); fprintf(fid, '%s\n', 'Susg'); fprintf(fid, '%s\n', 'Svsg'); elseif project.XB.outputType == 4 fprintf(fid, '%s\n', 'nglobalvar = 14'); fprintf(fid, '%s\n', 'H'); fprintf(fid, '%s\n', 'zs'); fprintf(fid, '%s\n', 'u'); fprintf(fid, '%s\n', 'v'); fprintf(fid, '%s\n', 'zb'); fprintf(fid, '%s\n', 'thetamean'); fprintf(fid, '%s\n', 'E'); fprintf(fid, '%s\n', 'D'); fprintf(fid, '%s\n', 'Qb'); fprintf(fid, '%s\n', 'Sk'); fprintf(fid, '%s\n', 'As'); fprintf(fid, '%s\n', 'Df'); fprintf(fid, '%s\n', 'Dp'); fprintf(fid, '%s\n', 'hh'); elseif project.XB.outputType == 5 fprintf(fid, '%s\n', 'nglobalvar = 4'); fprintf(fid, '%s\n', 'H'); fprintf(fid, '%s\n', 'zb'); fprintf(fid, '%s\n', 'zs'); fprintf(fid, '%s\n', 'gwlevel'); elseif project.XB.outputType == 6 fprintf(fid, '%s\n', 'nglobalvar = 2'); fprintf(fid, '%s\n', 'H'); fprintf(fid, '%s\n', 'zs'); end if project.XB.NetCDF == 1 fprintf(fid, '%s\n', 'outputformat = netcdf'); fprintf(fid, '%s\n', 'tunits = seconds since 1970-01-01 +1'); else fprintf(fid, '%s\n', 'outputformat = fortran'); fprintf(fid, '%s\n', 'tunits = seconds since 1970-01-01 +1'); end %Groundwater flow if sed.XB.gwflow == 1 fprintf(fid, '%s\n', ['gwflow = ', num2str(sed.XB.gwflow)]) if sed.XB.gw0 == -99 && exist('tides.waterlevel') == 1 if exist('tides.waterlevel') fprintf(fid, '%s\n', ['gw0 = ', num2str(nanmean(tides.waterlevel))]); else fprintf(fid, '%s\n', ['gw0 = 0']); end elseif sed.XB.gw0 == -88 if exist('tides.waterlevel') [~, peakMag] = peakfinder(tides.waterlevel); fprintf(fid, '%s\n', ['gw0 = ', num2str(nanmean(peakMag))]); else fprintf(fid, '%s\n', ['gw0 = 0']); end else fprintf(fid, '%s\n', ['gw0 = ', num2str(sed.XB.gw0)]); end end %Vegetation if veg.XB.vegUse == 1 fprintf(fid, '%s\n', ['nveg = 1']) fprintf(fid, '%s\n', ['veggiefile = veggiefile.txt']) fprintf(fid, '%s\n', ['veggiemapfile = veggiemap.txt']) end %Grain Size and Multiple Sediment Fractions % if sed.ngd >1 %layers are not yet implemented in toolbox, so this is not super relevant % fprintf(fid, '%s\n', ['ngd = ', num2str(sed.ngd)]); % fprintf(fid, '%s\n', ['D90 = ', num2str(sed.D90)]); % fprintf(fid, '%s\n', ['D50 = ', num2str(sed.D50)]); % if exist('sed.D10') ==1 % fprintf(fid, '%s\n', ['D10 = ', num2str(sed.D15)]); % end % fprintf(fid, '%s\n', ['nd = 3']); % fprintf(fid, '%s\n', ['dzg1 = ', num2str(sed.dzg1)]); % fprintf(fid, '%s\n', ['dzg2 = ', num2str(sed.dzg2)]); % fprintf(fid, '%s\n', ['dzg3 = ', num2str(sed.dzg3)]); % fprintf(fid, '%s\n', ['sedcal = ', num2str(sed.sedcal)]); % else % put in grain size info into model fprintf(fid, '%s\n', ['D90 = ', num2str(sed.XB.D90(1))]); fprintf(fid, '%s\n', ['D50 = ', num2str(sed.XB.D50(1))]); if exist('sed.D10') == 1 fprintf(fid, '%s\n', ['D15 = ', num2str(sed.XB.D10(1))]); end % end %NON-DEFAULT VARIABLES % if project.XB.default == 0 %Wave params % if regimes.wave_type(run_number) == 2 % fprintf(fid, '%s\n', ['break = 2']); %cant use all wave breaking formulas for stationary case % else fprintf(fid, '%s\n', ['break = ', num2str(waves.XB.break)]); % end fprintf(fid, '%s\n', ['gamma = ', num2str(waves.XB.gamma)]); fprintf(fid, '%s\n', ['gammax = ', num2str(waves.XB.gammax)]); fprintf(fid, '%s\n', ['alpha = ', num2str(waves.XB.alpha)]); fprintf(fid, '%s\n', ['breakerdelay = ', num2str(waves.XB.breakerdelay)]); fprintf(fid, '%s\n', ['roller = ', num2str(waves.XB.roller)]); fprintf(fid, '%s\n', ['beta = ', num2str(waves.XB.beta)]); fprintf(fid, '%s\n', ['rfb = ', num2str(waves.XB.rfb)]); fprintf(fid, '%s\n', ['shoaldelay = ', num2str(waves.XB.shoaldelay)]); fprintf(fid, '%s\n', ['n = ',num2str(waves.XB.n)]); fprintf(fid, '%s\n', ['wci = ',num2str(waves.XB.wci)]); fprintf(fid, '%s\n', ['hwci = ',num2str(waves.XB.hwci)]); fprintf(fid, '%s\n', ['cats = ',num2str(waves.XB.cats)]); fprintf(fid, '%s\n', ['taper = ',num2str(waves.XB.taper)]); %Wind fprintf(fid, '%s\n', ['wind = ',num2str(winds.XB.windUse)]); if winds.XB.windUse == 1 fprintf(fid, '%s\n', ['windv = ',num2str(winds.windspeed(run_number))]); %note that wind direction is nautical for xbeach, whereas 0 is convention for other models tempwinddir = winds.winddir(run_number); tempwinddir = wrapTo360(270-tempwinddir); fprintf(fid, '%s\n', ['windth = ',num2str(tempwinddir)]); fprintf(fid, '%s\n', ['rhoa = ',num2str(winds.XB.rhoa)]); fprintf(fid, '%s\n', ['Cd = ',num2str(winds.XB.Cd)]); end %Sed Params fprintf(fid, '%s\n', ['waveform = ', num2str(sed.XB.waveform)]); %fprintf(fid, '%s\n', ['form = ', num2str(sed.XB.form)]) if sed.XB.hmin>0 fprintf(fid, '%s\n', ['hmin = ', num2str(sed.XB.hmin)]); else fprintf(fid, '%s\n', ['hmin = ', num2str(waves.XB.eps)]); end fprintf(fid, '%s\n', ['turb = ', num2str(sed.XB.turb)]); fprintf(fid, '%s\n', ['rhos = ', num2str(sed.XB.rhos)]); fprintf(fid, '%s\n', ['por = ', num2str(sed.XB.por)]); fprintf(fid, '%s\n', ['sourcesink = ', num2str(sed.XB.sourcesink)]); fprintf(fid, '%s\n', ['thetanum = ', num2str(sed.XB.thetanum)]); fprintf(fid, '%s\n', ['cmax = ', num2str(sed.XB.cmax)]); %fprintf(fid, '%s\n', ['lwt = ', num2str(sed.XB.lwt)]) fprintf(fid, '%s\n', ['betad = ', num2str(sed.XB.betad)]); fprintf(fid, '%s\n', ['sus = ', num2str(sed.XB.sus)]); fprintf(fid, '%s\n', ['bed = ', num2str(sed.XB.bed)]); fprintf(fid, '%s\n', ['bulk = ', num2str(sed.XB.bulk)]); %fprintf(fid, '%s\n', ['lws = ', num2str(sed.XB.lws)]) fprintf(fid, '%s\n', ['sws = ', num2str(sed.XB.sws)]); fprintf(fid, '%s\n', ['BRfac = ', num2str(sed.XB.BRfac)]); fprintf(fid, '%s\n', ['facsl = ', num2str(sed.XB.facsl)]); fprintf(fid, '%s\n', ['bdslpeffmag = ', sed.XB.bdslpeffmag]); fprintf(fid, '%s\n', ['bdslpeffdir = ', sed.XB.bdslpeffdir]); fprintf(fid, '%s\n', ['bdslpeffini = ', sed.XB.bdslpeffini]); fprintf(fid, '%s\n', ['bdslpeffdirfac = ', num2str(sed.XB.bdslpeffdirfac)]); fprintf(fid, '%s\n', ['ucrcal = ', num2str(sed.XB.ucrcal)]); fprintf(fid, '%s\n', ['fallvelred = ', num2str(sed.XB.fallvelred)]); fprintf(fid, '%s\n', ['facDc = ', num2str(sed.XB.facDc)]); fprintf(fid, '%s\n', ['turbadv = ', sed.XB.turbadv]); fprintf(fid, '%s\n', ['z0 = ', num2str(sed.XB.z0)]); fprintf(fid, '%s\n', ['smax = ', num2str(sed.XB.smax)]); fprintf(fid, '%s\n', ['tsfac = ', num2str(sed.XB.tsfac)]); fprintf(fid, '%s\n', ['Tbfac = ', num2str(sed.XB.Tbfac)]); fprintf(fid, '%s\n', ['Tsmin = ', num2str(sed.XB.Tsmin)]); if sed.XB.q3d == 1 fprintf(fid, '%s\n', ['q3d = 1']) fprintf(fid, '%s\n', ['vonkar = ', num2str(sed.XB.vonkar)]); fprintf(fid, '%s\n', ['vicmol = ', num2str(sed.XB.vicmol)]); fprintf(fid, '%s\n', ['kmax = ', num2str(sed.XB.kmax)]); fprintf(fid, '%s\n', ['sigfac = ', num2str(sed.XB.sigfac)]); end %Flow fprintf(fid, '%s\n', ['bedfriction = ', flow.XB.bedfriction]); fprintf(fid, '%s\n', ['bedfriccoef = ', num2str(flow.XB.bedfriccoef)]); fprintf(fid, '%s\n', ['nuh = ', num2str(flow.XB.nuh)]); fprintf(fid, '%s\n', ['dilatancy = ', num2str(sed.XB.dilatancy)]); %EXPERIMENTAL CODE fprintf(fid, '%s\n', ['lsgrad = ', num2str(sed.XB.lsgrad)]); fclose(fid); end
github
ncohn/Windsurf-master
cdm_veg_routine_1d.m
.m
Windsurf-master/SubRoutines/cdm_veg_routine_1d.m
1,548
utf_8
4273ab78df05e8eb850f62b862d6004a
%cdm_veg_routine.m - Re-implementation of Coastal Dune Model (CDM) vegetation growth rate within Matlab %Created By: N. Cohn, Oregon State University and E. Goldstein, University of North Carolina Chapel Hill function [veggie_matrix] = cdm_veg_routine_1d(project, veg, grids, veggie_matrix, dhdt, xmin) %INPUT ARGUMENTS %veggie_matrix = the percent cover of vegetation (i.e., previous timestep) %dhdt = the change in topography that occured in the current timestep %OUTPUT ARGUMENTS %veggie_matrix = the new percent cover of vegetation timefrac = 1; %set time frac as one here so that mimics real world time timeStep_days = project.timeStep/(24*60*60); %the Tveg is a growth rate in days, so time units need to be consistent within this routine %define the growrate V_gen = 1/veg.CDM.Tveg; shorefactor = ones(1, grids.nx); %growth from growth rate and deposition sensParam = 1; %sensitivity to burial parameter; hardcoded for now but should add as a user-defined parameter at some point dV = ((1 - veggie_matrix(:)) * V_gen .* shorefactor(:))- (abs(dhdt(:)) * sensParam); %cover fraction evolves (timefrac is the rescaled wind time) veggie_matrix= veggie_matrix(:) + (timeStep_days(:) * dV(:) * timefrac(:)); %limiting conditions % can't have cover density greater than rhomax or less than 0)) veggie_matrix(veggie_matrix > veg.CDM.maximumDensity) = veg.CDM.maximumDensity; veggie_matrix(veggie_matrix < 0) = 0; veggie_matrix(1:xmin) = 0; end
github
ncohn/Windsurf-master
cdm_run.m
.m
Windsurf-master/SubRoutines/cdm_run.m
3,386
utf_8
978dfd4a0e7bdb5a6d1eaa65abe42c08
%cdm_params.m - Code to run Coastal Dune Model (CDM) parameter file for Windsurf coupler %Created By: N. Cohn, Oregon State University function output = cdm_run(project, idx) %Run the simulation if numel(project.CDM.CDMExecutable)>3 if isunix == 1 try %try up to 3 times because of bang-poll error on Centos7 system([project.CDM.CDMExecutable ' cdm.par > /dev/null']); catch err try pause(1); system([project.CDM.CDMExecutable ' cdm.par > /dev/null']); catch err pause(1); system([project.CDM.CDMExecutable ' cdm.par > /dev/null']); end end else system([project.CDM.CDMExecutable, ' cdm.par > command_line_cdm.txt']); end else %if no value given for where the CDM EXE is assume its in the path system('Dune cdm.par > command_line_cdm.txt'); end %Load and store the output try output = load_cdm(project); catch err try pause(2) %need to add in a short pause between runs b/c model needs time to write out, 1 s seems to be plenty output = load_cdm(project); catch err try pause(5) output = load_cdm(project); catch err pause(60) output = load_cdm(project); end end end end function output = load_cdm(project) %pick the last output file if project.flag.CDM ~=2 output_num = project.timeStep/project.CDM.timestep; else output_num = 1; %only run for 1 time step if only pulling out wind end output.h = load([project.Directory, filesep, 'cdm', filesep, 'CDM_temp', filesep, 'h.', sprintf('%05d',output_num),'.dat']); output.veget_x = load([project.Directory, filesep,'cdm', filesep,'CDM_temp', filesep, 'veget_x.', sprintf('%05d',output_num),'.dat']); output.shear_x = load([project.Directory, filesep,'cdm', filesep,'CDM_temp', filesep, 'shear_x.', sprintf('%05d',output_num),'.dat']); output.u_x = load([project.Directory, filesep,'cdm', filesep,'CDM_temp', filesep, 'u_x.', sprintf('%05d',output_num),'.dat']); % output.flux_x = load([project.Directory, filesep, 'cdm', filesep,'CDM_temp', filesep, 'flux_x.', sprintf('%05d',output_num),'.dat']); output.stall = load([project.Directory, filesep, 'cdm', filesep,'CDM_temp', filesep, 'stall.', sprintf('%05d',output_num),'.dat']); output.shear_pert_x = load([project.Directory, filesep, 'cdm', filesep,'CDM_temp', filesep, 'shear_pert_x.', sprintf('%05d',output_num),'.dat']); output.h_sep = load([project.Directory, filesep, 'cdm', filesep,'CDM_temp', filesep, 'h_sep.', sprintf('%05d',output_num),'.dat']); %output.u_y = load([project.Directory, filesep,'cdm', filesep,'CDM_temp', filesep, 'u_y.', sprintf('%05d',output_num),'.dat']); %output.shear_y = load([project.Directory, filesep,'cdm', filesep,'CDM_temp', filesep, 'shear_y.', sprintf('%05d',output_num),'.dat']); %output.shear_pert_y = load([project.Directory, filesep,'cdm', filesep,'CDM_temp', filesep, 'shear_pert_y.', sprintf('%05d',output_num),'.dat']); end
github
brianhhu/FG_RNN-master
normalizeImage.m
.m
FG_RNN-master/mfiles/normalizeImage.m
1,043
utf_8
49b43f9266877e51fbc39a8c78e6ca59
% normalizeImage - linearly normalize an array. % % res = normalizeImage(data); % Linearly normalize data between 0 and 1. % % res = normalizeImage(img,range); % Lineary normalize data between range(1) and range(2) % instead of [0,1]. The special value range = [0 0] % means that no normalization is performed, i.e., res = img. % This file is part of the SaliencyToolbox - Copyright (C) 2006-2008 % by Dirk B. Walther and the California Institute of Technology. % See the enclosed LICENSE.TXT document for the license agreement. % More information about this project is available at: % http://www.saliencytoolbox.net function res = normalizeImage(img,varargin) if (length(varargin) >= 1) range = varargin{1}; else range = [0,1]; end if ((range(1) == 0) & (range(2) == 0)) res = img; return; end mx = max(img(:)); mn = min(img(:)); if (mx == mn) if mx == 0 res = img.*0; else res = img - mx + 0.5*sum(range); end else res = (img - mn) / (mx - mn) * abs(range(2)-range(1)) + min(range); end
github
brianhhu/FG_RNN-master
safeDivide.m
.m
FG_RNN-master/mfiles/safeDivide.m
561
utf_8
7ac0a35b93ad9811c932d0fbacf398ce
% safeDivide - divides two arrays, checking for 0/0. % % result = safeDivide(arg1,arg2) % returns arg1./arg2, where 0/0 is assumed to be 0 instead of NaN. % This file is part of the SaliencyToolbox - Copyright (C) 2006-2008 % by Dirk B. Walther and the California Institute of Technology. % See the enclosed LICENSE.TXT document for the license agreement. % More information about this project is available at: % http://www.saliencytoolbox.net function result = safeDivide(arg1,arg2) ze = (arg2 == 0); arg2(ze) = 1; result = arg1./arg2; result(ze) = 0;
github
brianhhu/FG_RNN-master
configureSimpleCell.m
.m
FG_RNN-master/other/CORFPushPull/configureSimpleCell.m
3,124
utf_8
f9cc38ffdf37e6625e5e696ee5add0c9
function filterModel = configureSimpleCell(sigma,sigmaRatio,t2) % create a synthetic stimulus of a vertical edge stimulus = zeros(200); stimulus(:,1:100) = 1; params.eta = 1; params.radius = ceil(sigma*2.5)*2+1; % Apply DoG filter DoG(:,:,1) = getDoG(stimulus, sigma, 0, sigmaRatio, 1, 0); DoG(:,:,2) = -DoG(:,:,1); % Half wave rectification DoG(:,:,1) = DoG(:,:,1) .* (DoG(:,:,1) > 0); DoG(:,:,2) = DoG(:,:,2) .* (DoG(:,:,2) > 0); % Choose rho list according to given sigma value if sigma >= 1 && sigma <= 2 params.rho = [14.38 6.9796 3.0310 1.4135]; elseif sigma > 2 && sigma < 2.4 params.rho = [19.18 9.369 4.5128 2.1325]; elseif sigma >= 2.4 && sigma <= 3.5 params.rho = [24.62 12.6488 6.1992 3.0515]; elseif sigma >= 4 && sigma <= 5 params.rho = [34.43 18.08 9.2467 4.7877 3.3021]; end params.alpha = 0.9; % Create configuration set fp = [100,100]; simpleCell.excitation = []; for r = 1:length(params.rho) [onoff, rho, phi] = determineProperties(DoG,params.rho(r),params.eta,fp,t2); if ~isempty(onoff) simpleCell.excitation = [simpleCell.excitation [onoff; repmat(sigma,1,length(onoff)); rho; phi]]; end end simpleCell.excitation(4,:) = mod(simpleCell.excitation(4,:),2*pi); params.sigma0 = 2; params.sigmaRatio = sigmaRatio; filterModel.params = params; filterModel.params.radius = round(max(params.rho) + (2 + params.alpha*max(params.rho))/2); filterModel.simpleCell = simpleCell; function [onoff, rho, phi] = determineProperties(input,rho,eta,fp,t2) gb = max(input,[],3); t = inf; for i = 1:size(input,3) mxlist = max(max(input(:,:,i))); if mxlist < t t = mxlist; end end t = min(mxlist); x = 1:360*2; if rho > 0 y = gb(sub2ind([size(input,1),size(input,2)],round(fp(1) + rho.*cos(x.*pi/180)),round(fp(2)+(rho.*sin(x.*pi/180))))); y = circshift(y',270)'; if length(unique(y)) == 1 onoff = []; rho = []; phi = []; return; end y(y < 0.01) = 0; y = round(y*1000)/1000; BW = bwlabel(imregionalmax(y)); npeaks = max(BW(:)); peaks = zeros(1,npeaks); for i = 1:npeaks peaks(i) = mean(find(BW == i)); end f = peaks >= 180 & peaks < 540; phivalues = peaks(f); if phivalues(1)+360 - phivalues(end) < eta if P(locs(uidx(1))) < P(locs(uidx(end))) phivalues(1) = []; else phivalues(end) = []; end end [x, y] = pol2cart((phivalues-270)*pi/180,rho); phi = phivalues*pi/180; onoff = zeros(1,numel(phi)); for i = 1:numel(phi) [ignore idx] = max(input(round(fp(2)+x(i)),round(fp(1)+y(i)),:)); onoff(i) = idx-1; end else centreResponses = reshape(input(round(fp(2)),round(fp(1)),:),1,2); mx = max(centreResponses,[],1); if max(mx) >= t onoff = find(mx > t2*max(mx)) - 1; phi = zeros(1,length(onoff)); else onoff = []; phi = []; end end rho = repmat(rho,1,length(phi));
github
brianhhu/FG_RNN-master
getSimpleCellResponse.m
.m
FG_RNN-master/other/CORFPushPull/getSimpleCellResponse.m
4,839
utf_8
75601e8e2b2491a784044c4e348dec9a
function [response, responseParams] = getSimpleCellResponse(img,model,orientlist,inhibitionFactor,responseParams) % Compute all blurred responses and store the results in a hash table for % fast retrieval. This can be implemented in a parallel mode. if nargin == 4 [SimpleCellHashTable, weightsigma] = computeBlurredResponse(img,model); responseParams.SimpleCellHashTable = SimpleCellHashTable; responseParams.weightsigma = weightsigma; else SimpleCellHashTable = responseParams.SimpleCellHashTable; weightsigma = responseParams.weightsigma; end response = zeros(size(img,1),size(img,2),numel(orientlist)); for i = 1:numel(orientlist) rotmodel.simpleCell.excitation = modifyModel(model.simpleCell.excitation,'thetaoffset',orientlist(i)*pi/180); if isfield(model.simpleCell,'inhibition') rotmodel.simpleCell.inhibition = modifyModel(model.simpleCell.inhibition,'thetaoffset',orientlist(i)*pi/180); end % Compute the excitatory response of the simple cell excitationresponse = getResponse(SimpleCellHashTable,rotmodel.simpleCell.excitation,weightsigma,model.params); if isfield(model.simpleCell,'inhibition') % Compute the antiphase inhibitory response of the simple cell inhibitionresponse = getResponse(SimpleCellHashTable,rotmodel.simpleCell.inhibition,weightsigma,model.params); % Compute the net response rotresponse = excitationresponse - inhibitionFactor*inhibitionresponse; rotresponse = rotresponse .* (rotresponse > 0); else % If no inhibition, then we only take the excitatory response rotresponse = excitationresponse; end response(:,:,i) = rotresponse; end function response = getResponse(SimpleCellHashTable,simpleCell,weightsigma,params) ntuples = size(simpleCell,2); w = zeros(1,ntuples); response = 1; for i = 1:ntuples delta = simpleCell(1,i); sigma = simpleCell(2,i); rho = round(simpleCell(3,i)*1000)/1000; phi = simpleCell(4,i); [col, row] = pol2cart(phi,rho); blurredResponse = SimpleCellHashTable(getHashKey([delta sigma rho])); shiftedResponse = imshift(blurredResponse,fix(row),-fix(col)); w(i) = exp(-rho^2/(2*weightsigma*weightsigma)); response = response .* shiftedResponse; end response = response.^(1/sum(w)); %response = response .^ (1/ntuples); response = response(params.radius+1:end-params.radius,params.radius+1:end-params.radius); function [SimpleCellHashTable, weightsigma] = computeBlurredResponse(img,model) sigmaList = model.simpleCell.excitation(2,:); paramsList = model.simpleCell.excitation([1 2 3],:)'; if isfield(model.simpleCell,'inhibition') sigmaList = [sigmaList model.simpleCell.inhibition(2,:)]; paramsList = [paramsList; model.simpleCell.inhibition([1 2 3],:)']; end sigmaList = unique(sigmaList); paramsList = unique(round(paramsList*1000)/1000,'rows'); nsigmaList = numel(sigmaList); nparamsList = size(paramsList,1); LGNKeyList = cell(1,nsigmaList*2); LGNValueList = cell(1,nsigmaList*2); idx = 1; for s = 1:nsigmaList delta = 0; LGNValueList{idx} = getDoG(img,sigmaList(s),0,model.params.sigmaRatio,delta,model.params.radius); LGNKeyList{idx} = getHashKey([delta sigmaList(s)]); delta = 1; LGNValueList{idx+1} = -LGNValueList{idx}; LGNKeyList{idx+1} = getHashKey([delta sigmaList(s)]); LGNValueList{idx} = LGNValueList{idx} .* (LGNValueList{idx} > 0); LGNValueList{idx+1} = LGNValueList{idx+1} .* (LGNValueList{idx+1} > 0); idx = idx + 2; end LGNHashTable = containers.Map(LGNKeyList,LGNValueList); SimpleCellKeyList = cell(1,nparamsList); SimpleCellValueList = cell(1,nparamsList); weightsigma = max(paramsList(:,3)) / 3; for p = 1:nparamsList delta = paramsList(p,1); sigma = paramsList(p,2); rho = paramsList(p,3); SimpleCellKeyList{p} = getHashKey([delta sigma rho]); LGNHashKey = getHashKey([delta sigma]); LGN = LGNHashTable(LGNHashKey); r = round((model.params.sigma0 + model.params.alpha*rho)/2); if r > 0 if strcmp(model.params.blurringType,'Sum') smoothfilter = fspecial('gaussian',[2*r+1,2*r+1],r/3); SimpleCellValueList{p} = conv2(LGN,smoothfilter,'same'); elseif strcmp(model.params.blurringType,'Max') SimpleCellValueList{p} = maxgaussianfilter(LGN,r/3,0,0,[1 1],size(LGN)); end else SimpleCellValueList{p} = LGN; end SimpleCellValueList{p} = SimpleCellValueList{p} .^ exp(-rho^2/(2*weightsigma*weightsigma)); %SimpleCellValueList{p} = SimpleCellValueList{p} .^ exp(-rho^2/(2*weightsigma*weightsigma)); end SimpleCellHashTable = containers.Map(SimpleCellKeyList,SimpleCellValueList);
github
brianhhu/FG_RNN-master
CORFContourDetection.m
.m
FG_RNN-master/other/CORFPushPull/CORFContourDetection.m
3,797
UNKNOWN
cb2e6616a8479085cd4db36c756309e6
% CORFContourDetection Compute contour map % % Input: % img - a coloured or grayscale image % sigma - The standard deviation of the DoG functions used % beta - The increase in the distance between the sets of center-on % and ceter-off DoG receptive fields. % inhibitionFactor - The factor by which the response exhibited in the % inhibitory receptive field suppresses the response exhibited in the % excitatory receptive field % highthresh - The high threshold of the non-maximum suppression used % for binarization % Output: % binarymap - The binary map containing the contours % corfresponse - The response map of the rotation-invariant CORF operator % % Usage example: % [binmap, corfresponse] = CORFContourDetection(imread('./img/134052.jpg'),2.2,4,1.8,0.007); % figure;imagesc(imcomplement(binmap));axis image;axis off;colormap(gray); % figure;imagesc(corfresponse);axis image;axis off;colormap(gray); % % [binmap, corfresponse] = CORFContourDetection(imread('./img/rino.pgm'),2.2,4,1.8,0.005); % figure;imagesc(imcomplement(binmap));axis image;axis off;colormap(gray); % figure;imagesc(corfresponse);axis image;axis off;colormap(gray); % % You are invited to use this Matlab script and cite the following articles: % Azzopardi G, Rodr�guez-S�nchez A, Piater J, Petkov N (2014) A Push-Pull CORF Model of a Simple Cell % with Antiphase Inhibition Improves SNR and Contour Detection. PLoS ONE 9(7): e98424. % doi:10.1371/journal.pone.0098424 % % Azzopardi G, Petkov N (2012) A CORF Computational Model of a Simple Cell that relies on LGN Input % Outperforms the Gabor Function Model. Biological Cybernetics 1?13. doi: 10.1007/s00422-012-0486-6 % function [binarymap, corfresponse] = CORFContourDetection(img,sigma, beta, inhibitionFactor, highthresh) function [binarymap, output, corfresponse, oriensMatrix] = CORFContourDetection(img,sigma, beta, inhibitionFactor, highthresh) %%%%%%%%%%%%%%%% BEGIN CONFIGURATION %%%%%%%%%%%%%%%%%% % Add Utilities folder to path % addpath('./Utilities/'); if ndims(img) == 3 img = rgb2gray(img); end img = rescaleImage(double(img),0,1); % Create CORF model simple cell CORF = configureSimpleCell(sigma,0.5,0.5); % create the inhibitory cell CORF.simpleCell.inhibition = modifyModel(CORF.simpleCell.excitation,'invertpolarity',1,'overlappixels',beta); %%%%%%%%%%%%%%%% END CONFIGURATION %%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% BEGIN APPLICATION %%%%%%%%%%%%%%%%%%% orienslist = 0:22.5:337.5;%0:30:330; % change to 8 orientations CORF.params.blurringType = 'Sum'; % compute CORF response image for each orientation given in orienslist output = getSimpleCellResponse(img,CORF,orienslist,inhibitionFactor); % combine the output of all orientations [corfresponse, oriensMatrix] = calc_viewimage(output,1:numel(orienslist), orienslist*pi/180); %%%%%%%%%%%%%%%%% END APPLICATION %%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% BEGIN BINARIZATION %%%%%%%%%%%%%%%%%% % compute thinning thinning = calc_thinning(corfresponse, oriensMatrix, 1); % Choose high threshold of hysteresis thresholding if nargin == 4 bins = 64;p = 0.3; % bh %0.1; %Keep the strongest 10% of the pixels in the resulting thinned image f = find(thinning > 0); counts = imhist(thinning(f),bins); highthresh = find(cumsum(counts) > (1-p)*length(f),1,'first') / bins; end binarymap = calc_hysteresis(thinning, 1, 0.5*highthresh, highthresh); % show binarized image % figure; % subplot(1,2,1);imagesc(img);axis off;axis image;colormap(gray); % subplot(1,2,2);imagesc(imcomplement(binarymap));axis off;axis image;colormap(gray); %%%%%%%%%%%%%%%%% END BINARIZATION %%%%%%%%%%%%%%%%%%%%
github
brianhhu/FG_RNN-master
hysthresh.m
.m
FG_RNN-master/other/CORFPushPull/Utilities/hysthresh.m
3,438
utf_8
564ed52aa191fbb399daf6f3b0accddb
% HYSTHRESH - Hysteresis thresholding % % Usage: bw = hysthresh(im, T1, T2) % % Arguments: % im - image to be thresholded (assumed to be non-negative) % T1 - upper threshold value % T2 - lower threshold value % % Returns: % bw - the thresholded image (containing values 0 or 1) % % Function performs hysteresis thresholding of an image. % All pixels with values above threshold T1 are marked as edges % All pixels that are adjacent to points that have been marked as edges % and with values above threshold T2 are also marked as edges. Eight % connectivity is used. % % It is assumed that the input image is non-negative % % Author: Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk @ csse uwa edu au http://www.csse.uwa.edu.au/~pk % % December 1996 - Original version % March 2001 - Speed improvements made (~4x) % % A stack (implemented as an array) is used to keep track of all the % indices of pixels that need to be checked. % Note: For speed the number of conditional tests have been minimised % This results in the top and bottom edges of the image being considered to % be connected. This may cause some stray edges to be propagated further than % they should be from the top or bottom. % function bw = hysthresh(im, T1, T2) if (T2 > T1 | T2 < 0 | T1 < 0) % Check thesholds are sensible error('T1 must be >= T2 and both must be >= 0 '); end [rows, cols] = size(im); % Precompute some values for speed and convenience. rc = rows*cols; rcmr = rc - rows; rp1 = rows+1; bw = im(:); % Make image into a column vector pix = find(bw >= T1); % Find indices of all pixels with value > T1 npix = size(pix,1); % Find the number of pixels with value > T1 stack = zeros(rows*cols,1); % Create a stack array (that should never % overflow!) stack(1:npix) = pix; % Put all the edge points on the stack stp = npix; % set stack pointer for k = 1:npix bw(pix(k)) = -1; % mark points as edges end % Precompute an array, O, of index offset values that correspond to the eight % surrounding pixels of any point. Note that the image was transformed into % a column vector, so if we reshape the image back to a square the indices % surrounding a pixel with index, n, will be: % n-rows-1 n-1 n+rows-1 % % n-rows n n+rows % % n-rows+1 n+1 n+rows+1 O = [-1, 1, -rows-1, -rows, -rows+1, rows-1, rows, rows+1]; while stp ~= 0 % While the stack is not empty v = stack(stp); % Pop next index off the stack stp = stp - 1; if v > rp1 & v < rcmr % Prevent us from generating illegal indices % Now look at surrounding pixels to see if they % should be pushed onto the stack to be % processed as well. index = O+v; % Calculate indices of points around this pixel. for l = 1:8 ind = index(l); if bw(ind) > T2 % if value > T2, stp = stp+1; % push index onto the stack. stack(stp) = ind; bw(ind) = -1; % mark this as an edge point end end end end bw = (bw == -1); % Finally zero out anything that was not an edge bw = reshape(bw,rows,cols); % and reshape the image
github
HidekiKawahara/SparkNG-master
recordingGUIV7.m
.m
SparkNG-master/GUI/recordingGUIV7.m
41,797
utf_8
f302ffad8218e87eea938f7f8fa92b5d
function varargout = recordingGUIV7(varargin) % Reconding GUI with realtime FFT analyzer and other viewers. Type: % recordingGUIV7 % to start. % Designed and coded by Hideki Kawahara (kawahara AT sys.wakayama-u.ac.jp) % 28/Nov./2013 % 29/Nov./2013 minor bug fix % 13/Dec./2013 spectrogram and playback functions are added. % 15/Dec./2013 scrubbing mode is added. % 21/Dec./2013 load button is added. % 17/April/2014 audio related I/O and other revisions % 03/May/2014 audio out is revised % 04/May/2014 alternate audo out server % 31/Aug./2015 machine independent and resizable % This work is licensed under the Creative Commons % Attribution 4.0 International License. % To view a copy of this license, visit % http://creativecommons.org/licenses/by/4.0/. % RECORDINGGUIV7 MATLAB code for recordingGUIV7.fig % RECORDINGGUIV7, by itself, creates a new RECORDINGGUIV7 or raises the existing % singleton*. % % H = RECORDINGGUIV7 returns the handle to a new RECORDINGGUIV7 or the handle to % the existing singleton*. % % RECORDINGGUIV7('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in RECORDINGGUIV7.M with the given input arguments. % % RECORDINGGUIV7('Property','Value',...) creates a new RECORDINGGUIV7 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before recordingGUIV7_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to recordingGUIV7_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 recordingGUIV7 % Last Modified by GUIDE v2.5 04-May-2014 07:46:29 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @recordingGUIV7_OpeningFcn, ... 'gui_OutputFcn', @recordingGUIV7_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 end % --- Executes just before recordingGUIV7 is made visible. function recordingGUIV7_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 recordingGUIV7 (see VARARGIN) %global handleForTimer; % Choose default command line output for recordingGUIV7 handles.output = hObject; % Update handles structure guidata(hObject, handles); %handles delete(timerfindall); %pause(0.05) initializeDisplay(handles); myGUIdata = guidata(handles.multiScopeMainGUI); %set(myGUIdata.largeViewTypePopup,'enable','off'); set(myGUIdata.saveButton,'enable','off'); set(myGUIdata.spectrogramHandle,'visible','off'); set(myGUIdata.sgramAxis,'visible','off'); set(myGUIdata.playAllButton,'enable','off'); set(myGUIdata.playVisibleButton,'enable','off'); set(myGUIdata.saveVisibleButton,'enable','off'); set(myGUIdata.playTFregion,'enable','off'); set(myGUIdata.loadButton,'enable','off'); %pause(0.5) timerEventInterval = 0.1; % in second timer50ms = timer('TimerFcn',@synchDrawGUI, 'Period',timerEventInterval,'ExecutionMode','fixedRate', ... 'userData',handles.multiScopeMainGUI); myGUIdata.timer50ms = timer50ms; timerEventIntervalForPlay = 0.10; % in second timerForPlayer = timer('TimerFcn',@audioTimerServer, 'Period',timerEventIntervalForPlay,'ExecutionMode','fixedRate', ... 'userData',handles.multiScopeMainGUI); myGUIdata.timerForPlayer = timerForPlayer; myGUIdata.player1 = audioplayer(zeros(1000,1),44100); myGUIdata.player2 = audioplayer(zeros(1000,1),44100); myGUIdata.player3 = audioplayer(zeros(1000,1),44100); myGUIdata.player4 = audioplayer(zeros(1000,1),44100); myGUIdata.player5 = audioplayer(zeros(1000,1),44100); myGUIdata.maximumNumberOfAudioPlayers = 3; myGUIdata.smallviewerWidth = 30; % 30 ms is defaule myGUIdata.samplingFrequency = 44100; myGUIdata.recordObj1 = audiorecorder(myGUIdata.samplingFrequency,24,1); myGUIdata.liveData = 'yes'; record(myGUIdata.recordObj1) switch get(myGUIdata.recordObj1,'Running') case 'on' stop(myGUIdata.recordObj1); end myGUIdata.pointerMode = 'normal'; myGUIdata.initializeScrubbing = 0; guidata(handles.multiScopeMainGUI,myGUIdata); startButton_Callback(hObject, eventdata, handles) % UIWAIT makes recordingGUIV7 wait for user response (see UIRESUME) % uiwait(handles.multiScopeMainGUI); end function audioTimerServer(obj, event, string_arg) %global handleForTimer; handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); visibleIndex = get(myGUIdata.cursorFringeHandle,'userdata'); switch myGUIdata.pointerMode case 'dragging' switch get(myGUIdata.withAudioRadioButton,'value') case 1 if ~isplaying(myGUIdata.player1) play(myGUIdata.player1,[visibleIndex(1) visibleIndex(end)]); %myGUIdata.player1 = audioplayer(myGUIdata.audioData(visibleIndex),myGUIdata.samplingFrequency); %play(myGUIdata.player1); elseif myGUIdata.maximumNumberOfAudioPlayers >= 2 && ~isplaying(myGUIdata.player2) play(myGUIdata.player2,[visibleIndex(1) visibleIndex(end)]); elseif myGUIdata.maximumNumberOfAudioPlayers >= 3 && ~isplaying(myGUIdata.player3) play(myGUIdata.player3,[visibleIndex(1) visibleIndex(end)]); elseif myGUIdata.maximumNumberOfAudioPlayers >= 4 && ~isplaying(myGUIdata.player4) play(myGUIdata.player4,[visibleIndex(1) visibleIndex(end)]); elseif myGUIdata.maximumNumberOfAudioPlayers >= 5 && ~isplaying(myGUIdata.player5) play(myGUIdata.player5,[visibleIndex(1) visibleIndex(end)]); end end; end; end function initializeDisplay(handles) myGUIdata = guidata(handles.multiScopeMainGUI); myGUIdata.maxAudioRecorderCount = 200; myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.maxLevelIndicator = -100*ones(myGUIdata.maxAudioRecorderCount,1); myGUIdata.yMax = 1; axes(myGUIdata.smallViewerAxis); myGUIdata.windowViewHandle = plot(randn(1000,1),'g-','linewidth',3); hold on; myGUIdata.smallViewerPlotHandle = plot(randn(1000,1),'b'); set(myGUIdata.smallViewerAxis,'xtick',[],'ytick',[]); axes(myGUIdata.largeViewerAxis); fs = 44100; dataLength = round(30/1000*fs); fftl = 2.0.^ceil(log2(dataLength)); fAxis = (0:fftl-1)/fftl*fs; w = blackman(dataLength); pw = 20*log10(abs(fft(randn(dataLength,1).*w,fftl)/sqrt(sum(w.^2)))); myGUIdata.axisType = 'Logarithmic'; myGUIdata.window = w; myGUIdata.fAxis = fAxis; switch myGUIdata.axisType case 'Linear' myGUIdata.largeViewerPlotHandle = plot(fAxis,pw);grid on; axis([0 fs/2 [-90 20]]); case 'Logarithmic' myGUIdata.largeViewerPlotHandle = semilogx(fAxis,pw);grid on; axis([10 fs/2 [-90 20]]); end; set(gca,'fontsize',15); xlabel('frequency (Hz)'); ylabel('level (dB)'); axes(myGUIdata.wholeViewerAxis); myGUIdata.wholeViewerHandle = plot(myGUIdata.maxLevelIndicator); axis([0 myGUIdata.maxAudioRecorderCount -100 0]); set(myGUIdata.wholeViewerAxis,'xtick',[],'ylim',[-80 0]);grid on; axes(myGUIdata.sgramAxis); myGUIdata.spectrogramHandle = imagesc(rand(1024,200));axis('xy'); hold on; myGUIdata.cursorFringeHandle = plot([180 180 220 220],[-5 1027 1027 -5],'g','linewidth',2); myGUIdata.cursorHandle = plot([200 200],[0 1024],'ws-','linewidth',4); hold off; axis('off') set(myGUIdata.sgramAxis,'visible','off') set(myGUIdata.cursorFringeHandle,'visible','off') set(myGUIdata.cursorFringeHandle,'userdata',[0 1]); set(myGUIdata.cursorHandle,'visible','off','userData',handles.multiScopeMainGUI); set(myGUIdata.cursotPositionText,'visible','off'); myGUIdata.channelMenuString = cellstr(get(myGUIdata.channelPopupMenu,'String')); set(myGUIdata.channelPopupMenu,'visible','off'); set(myGUIdata.withAudioRadioButton,'enable','off'); set(myGUIdata.withAudioRadioButton,'value',0); myGUIdata.player = audioplayer(zeros(1000,1),44100); myGUIdata.maximumNumberOfAudioPlayers = 1; for ii = 1:myGUIdata.maximumNumberOfAudioPlayers myGUIdata.audioPlayerGroup(ii) = audioplayer(zeros(1000,1),44100); end; guidata(handles.multiScopeMainGUI,myGUIdata); end function synchDrawGUI(obj, event, string_arg) %global handleForTimer; handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); myGUIdata.smallviewerWidth = get(myGUIdata.radiobutton10ms,'value')*10+ ... get(myGUIdata.radiobutton30ms,'value')*30+ ... get(myGUIdata.radiobutton100ms,'value')*100+ ... get(myGUIdata.radiobutton300ms,'value')*300; numberOfSamples = round(myGUIdata.smallviewerWidth*myGUIdata.samplingFrequency/1000); if get(myGUIdata.recordObj1,'TotalSamples') > numberOfSamples tmpAudio = getaudiodata(myGUIdata.recordObj1); currentPoint = length(tmpAudio); xdata = 1:numberOfSamples; fs = myGUIdata.samplingFrequency; %disp(myGUIdata.audioRecorderCount) if length(currentPoint-numberOfSamples+1:currentPoint) > 10 ydata = tmpAudio(currentPoint-numberOfSamples+1:currentPoint); myGUIdata.audioRecorderCount = myGUIdata.audioRecorderCount-1; set(myGUIdata.smallViewerPlotHandle,'xdata',xdata,'ydata',ydata); if myGUIdata.yMax < max(abs(ydata)) myGUIdata.yMax = max(abs(ydata)); else myGUIdata.yMax = myGUIdata.yMax*0.8; end; set(myGUIdata.smallViewerAxis,'xlim',[0 numberOfSamples],'ylim',myGUIdata.yMax*[-1 1]); fftl = 2^ceil(log2(numberOfSamples)); fAxis = (0:fftl-1)/fftl*fs; switch get(myGUIdata.windowTypePopup,'value') case 1 w = blackman(numberOfSamples); case 2 w = hamming(numberOfSamples); case 3 w = hanning(numberOfSamples); case 4 w = bartlett(numberOfSamples); case 5 w = ones(numberOfSamples,1); case 6 w = nuttallwin(numberOfSamples); otherwise w = blackman(numberOfSamples); end; windowView = w*myGUIdata.yMax*2-myGUIdata.yMax; set(myGUIdata.windowViewHandle,'xdata',xdata,'ydata',windowView); pw = 20*log10(abs(fft(ydata.*w,fftl)/sqrt(sum(w.^2)))); set(myGUIdata.largeViewerPlotHandle,'xdata',fAxis,'ydata',pw); myGUIdata.maxLevelIndicator(max(1,myGUIdata.maxAudioRecorderCount-myGUIdata.audioRecorderCount)) ... = max(20*log10(abs(ydata))); set(myGUIdata.wholeViewerHandle,'ydata',myGUIdata.maxLevelIndicator); else disp('overrun!') end; if myGUIdata.audioRecorderCount < 0 switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end stop(myGUIdata.recordObj1); record(myGUIdata.recordObj1); myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.maxLevelIndicator = 0; % switch get(myGUIdata.timer50ms,'running') % case 'on' % stop(myGUIdata.timer50ms) % end; switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); end end; guidata(handleForTimer,myGUIdata); else disp(['Recorded data is not enough! Skipping this interruption....at ' datestr(now,30)]); end; end % --- Outputs from this function are returned to the command line. function varargout = recordingGUIV7_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; end % --- Executes on button press in startButton. function startButton_Callback(hObject, eventdata, handles) % hObject handle to startButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %global handleForTimer myGUIdata = guidata(handles.multiScopeMainGUI); switch myGUIdata.liveData case 'no' myGUIdata.liveData = 'yes'; myGUIdata.samplingFrequency = 44100; end; stop(myGUIdata.timerForPlayer); set(myGUIdata.saveButton,'enable','off'); set(myGUIdata.startButton,'enable','off'); set(myGUIdata.stopButton,'enable','on'); set(myGUIdata.playAllButton,'enable','off'); set(myGUIdata.playVisibleButton,'enable','off'); set(myGUIdata.saveVisibleButton,'enable','off'); set(myGUIdata.playTFregion,'enable','off'); set(myGUIdata.loadButton,'enable','off'); set(myGUIdata.cursorHandle,'visible','off'); set(myGUIdata.cursorFringeHandle,'visible','off'); set(myGUIdata.scrubbingButton,'enable','off','value',0); set(myGUIdata.channelPopupMenu,'visible','off'); switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.maxLevelIndicator = -100*ones(myGUIdata.maxAudioRecorderCount,1); myGUIdata.yMax = 1; record(myGUIdata.recordObj1); datacursormode off switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); case 'on' otherwise disp('timer is bloken!'); end set(myGUIdata.sgramAxis,'visible','off') set(myGUIdata.spectrogramHandle,'visible','off') set(myGUIdata.wholeViewerAxis,'visible','on'); set(myGUIdata.zoomInTool,'enable','on'); set(myGUIdata.zoomOutTool,'enable','on'); set(myGUIdata.PanTool,'enable','on'); set(myGUIdata.dataCursorTool,'enable','on'); guidata(handles.multiScopeMainGUI,myGUIdata); end % --- Executes on button press in stopButton. function stopButton_Callback(hObject, eventdata, handles) % hObject handle to stopButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.multiScopeMainGUI); myGUIdata.audioData = getaudiodata(myGUIdata.recordObj1); %disp('timer ends') %set(myGUIdata.startButton,'enable','off'); set(myGUIdata.saveButton,'enable','on'); set(myGUIdata.startButton,'enable','on'); set(myGUIdata.stopButton,'enable','off'); set(myGUIdata.playAllButton,'enable','on'); set(myGUIdata.playVisibleButton,'enable','on'); set(myGUIdata.saveVisibleButton,'enable','on'); set(myGUIdata.loadButton,'enable','on'); datacursormode off switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) case 'off' otherwise disp('timer is bloken!'); end; stop(myGUIdata.recordObj1); myGUIdata.player1 = audioplayer(myGUIdata.audioData,myGUIdata.samplingFrequency); myGUIdata.player2 = audioplayer(myGUIdata.audioData,myGUIdata.samplingFrequency); myGUIdata.player3 = audioplayer(myGUIdata.audioData,myGUIdata.samplingFrequency); myGUIdata.player4 = audioplayer(myGUIdata.audioData,myGUIdata.samplingFrequency); myGUIdata.player5 = audioplayer(myGUIdata.audioData,myGUIdata.samplingFrequency); set(handles.multiScopeMainGUI,'pointer','watch');drawnow sgramStructure = stftSpectrogramStructure(myGUIdata.audioData,myGUIdata.samplingFrequency,15,2,'blackman'); set(myGUIdata.spectrogramHandle,'cdata',max(-80,sgramStructure.dBspectrogram),'visible','on', ... 'xdata',sgramStructure.temporalPositions,'ydata',sgramStructure.frequencyAxis); set(myGUIdata.sgramAxis,'visible','on', ... 'xlim',[sgramStructure.temporalPositions(1) sgramStructure.temporalPositions(end)], ... 'ylim',[sgramStructure.frequencyAxis(1) sgramStructure.frequencyAxis(end)]); set(myGUIdata.wholeViewerAxis,'visible','off'); set(handles.multiScopeMainGUI,'pointer','arrow');drawnow set(myGUIdata.playTFregion,'enable','on'); set(myGUIdata.scrubbingButton,'enable','on','value',0); start(myGUIdata.timerForPlayer); guidata(handles.multiScopeMainGUI,myGUIdata); end % --- Executes on selection change in windowTypePopup. function windowTypePopup_Callback(hObject, eventdata, handles) % hObject handle to windowTypePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns windowTypePopup contents as cell array % contents{get(hObject,'Value')} returns selected item from windowTypePopup myGUIdata = guidata(handles.multiScopeMainGUI); switch get(myGUIdata.timer50ms,'running') case 'off' myGUIdata.initializeScrubbing = 1; myGUIdata.pointerMode = 'dragging'; guidata(handles.multiScopeMainGUI,myGUIdata); windowMotionFcnForManipulation(handles.multiScopeMainGUI,eventdata) myGUIdata.pointerMode = 'normal'; guidata(handles.multiScopeMainGUI,myGUIdata); end; end % --- Executes during object creation, after setting all properties. function windowTypePopup_CreateFcn(hObject, eventdata, handles) % hObject handle to windowTypePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on button press in radiobutton10ms. function radiobutton10ms_Callback(hObject, eventdata, handles) % hObject handle to radiobutton10ms (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 radiobutton10ms myGUIdata = guidata(handles.multiScopeMainGUI); set(handles.radiobutton10ms,'value',1); set(handles.radiobutton30ms,'value',0); set(handles.radiobutton100ms,'value',0); set(handles.radiobutton300ms,'value',0); switch get(myGUIdata.timer50ms,'running') case 'off' myGUIdata.initializeScrubbing = 1; myGUIdata.pointerMode = 'dragging'; guidata(handles.multiScopeMainGUI,myGUIdata); windowMotionFcnForManipulation(handles.multiScopeMainGUI,eventdata) myGUIdata.pointerMode = 'normal'; guidata(handles.multiScopeMainGUI,myGUIdata); end; end % --- Executes on button press in radiobutton30ms. function radiobutton30ms_Callback(hObject, eventdata, handles) % hObject handle to radiobutton30ms (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 radiobutton30ms myGUIdata = guidata(handles.multiScopeMainGUI); set(handles.radiobutton10ms,'value',0); set(handles.radiobutton30ms,'value',1); set(handles.radiobutton100ms,'value',0); set(handles.radiobutton300ms,'value',0); switch get(myGUIdata.timer50ms,'running') case 'off' myGUIdata.initializeScrubbing = 1; myGUIdata.pointerMode = 'dragging'; guidata(handles.multiScopeMainGUI,myGUIdata); windowMotionFcnForManipulation(handles.multiScopeMainGUI,eventdata) myGUIdata.pointerMode = 'normal'; guidata(handles.multiScopeMainGUI,myGUIdata); end; end % --- Executes on button press in radiobutton100ms. function radiobutton100ms_Callback(hObject, eventdata, handles) % hObject handle to radiobutton100ms (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 radiobutton100ms myGUIdata = guidata(handles.multiScopeMainGUI); set(handles.radiobutton10ms,'value',0); set(handles.radiobutton30ms,'value',0); set(handles.radiobutton100ms,'value',1); set(handles.radiobutton300ms,'value',0); switch get(myGUIdata.timer50ms,'running') case 'off' myGUIdata.initializeScrubbing = 1; myGUIdata.pointerMode = 'dragging'; guidata(handles.multiScopeMainGUI,myGUIdata); windowMotionFcnForManipulation(handles.multiScopeMainGUI,eventdata) myGUIdata.pointerMode = 'normal'; guidata(handles.multiScopeMainGUI,myGUIdata); end; end % --- Executes on button press in radiobutton300ms. function radiobutton300ms_Callback(hObject, eventdata, handles) % hObject handle to radiobutton300ms (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 radiobutton300ms myGUIdata = guidata(handles.multiScopeMainGUI); set(handles.radiobutton10ms,'value',0); set(handles.radiobutton30ms,'value',0); set(handles.radiobutton100ms,'value',0); set(handles.radiobutton300ms,'value',1); switch get(myGUIdata.timer50ms,'running') case 'off' myGUIdata.initializeScrubbing = 1; myGUIdata.pointerMode = 'dragging'; guidata(handles.multiScopeMainGUI,myGUIdata); windowMotionFcnForManipulation(handles.multiScopeMainGUI,eventdata) myGUIdata.pointerMode = 'normal'; guidata(handles.multiScopeMainGUI,myGUIdata); end; end % --- Executes on selection change in axisTypePopup. function axisTypePopup_Callback(hObject, eventdata, handles) % hObject handle to axisTypePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns axisTypePopup contents as cell array % contents{get(hObject,'Value')} returns selected item from axisTypePopup myGUIdata = guidata(handles.multiScopeMainGUI); fs = myGUIdata.samplingFrequency; switch get(myGUIdata.axisTypePopup,'value') case 1 set(myGUIdata.largeViewerAxis,'xlim',[10 fs/2],'xscale','log'); case 2 set(myGUIdata.largeViewerAxis,'xlim',[0 fs/2],'xscale','linear'); case 3 set(myGUIdata.largeViewerAxis,'xlim',[0 10000],'xscale','linear'); case 4 set(myGUIdata.largeViewerAxis,'xlim',[0 8000],'xscale','linear'); case 5 set(myGUIdata.largeViewerAxis,'xlim',[0 4000],'xscale','linear'); otherwise set(myGUIdata.largeViewerAxis,'xlim',[10 fs/2],'xscale','log'); end; switch get(myGUIdata.timer50ms,'running') case 'off' myGUIdata.initializeScrubbing = 1; myGUIdata.pointerMode = 'dragging'; guidata(handles.multiScopeMainGUI,myGUIdata); windowMotionFcnForManipulation(handles.multiScopeMainGUI,eventdata) myGUIdata.pointerMode = 'normal'; guidata(handles.multiScopeMainGUI,myGUIdata); end; end % --- Executes during object creation, after setting all properties. function axisTypePopup_CreateFcn(hObject, eventdata, handles) % hObject handle to axisTypePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on button press in quitButton. function quitButton_Callback(hObject, eventdata, handles) % hObject handle to quitButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.multiScopeMainGUI); %disp('timer ends') switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) end; stop(myGUIdata.recordObj1); delete(myGUIdata.timer50ms); delete(myGUIdata.recordObj1); close(handles.multiScopeMainGUI); end % --- 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) myGUIdata = guidata(handles.multiScopeMainGUI); outFileName = ['audioIn' datestr(now,30) '.wav']; [file,path] = uiputfile(outFileName,'Save the captured data'); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 %okInd = 0; disp('Save is cancelled!'); return; end; end; %audiowrite(myGUIdata.audioData,myGUIdata.samplingFrequency,24,[path file]); audiowrite([path file],myGUIdata.audioData,myGUIdata.samplingFrequency,'BitsPerSample',24); end % --- Executes on button press in saveVisibleButton. function saveVisibleButton_Callback(hObject, eventdata, handles) % hObject handle to saveVisibleButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.multiScopeMainGUI); outFileName = ['audioInTrim' datestr(now,30) '.wav']; [file,path] = uiputfile(outFileName,'Save the visible data'); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 %okInd = 0; disp('Save is cancelled!'); return; end; end; xLimit = get(myGUIdata.sgramAxis,'xlim'); fs = myGUIdata.samplingFrequency; x = myGUIdata.audioData; x = x(max(1,min(length(x),round(fs*xLimit(1)):round(fs*xLimit(end))))); audiowrite([path file],x,fs,'BitsPerSample',24); end % --- Executes on button press in playAllButton. function playAllButton_Callback(hObject, eventdata, handles) % hObject handle to playAllButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.multiScopeMainGUI); x = myGUIdata.audioData; fs = myGUIdata.samplingFrequency; myGUIdata.player = audioplayer(x/max(abs(x))*0.9,fs); guidata(handles.multiScopeMainGUI,myGUIdata); play(myGUIdata.player); end % --- Executes on button press in playVisibleButton. function playVisibleButton_Callback(hObject, eventdata, handles) % hObject handle to playVisibleButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.multiScopeMainGUI); xLimit = get(myGUIdata.sgramAxis,'xlim'); fs = myGUIdata.samplingFrequency; x = myGUIdata.audioData; x = x(max(1,min(length(x),round(fs*xLimit(1)):round(fs*xLimit(end))))); myGUIdata.player = audioplayer(x/max(abs(x))*0.99,fs); guidata(handles.multiScopeMainGUI,myGUIdata); playblocking(myGUIdata.player); end % -------------------------------------------------------------------- function Untitled_1_Callback(hObject, eventdata, handles) % hObject handle to Untitled_1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) end % --- Executes on button press in playTFregion. function playTFregion_Callback(hObject, eventdata, handles) % hObject handle to playTFregion (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.multiScopeMainGUI); xLimit = get(myGUIdata.sgramAxis,'xlim'); yLimit = get(myGUIdata.sgramAxis,'ylim'); fs = myGUIdata.samplingFrequency; fqLow = min(fs/2,max(0,yLimit(1))); fqHigh = max(0,min(fs/2,yLimit(2))); if fqLow < 20 fftl = 2.0.^ceil(log2(fs/fqHigh*6)); fAxis = (0:fftl/2)'/fftl*fs; doubleFAxis = [fAxis(:);fAxis(end-1:-1:2)]; gain = 1*(abs(doubleFAxis)<fqHigh); % low pass filter elseif fqHigh > fs/2*0.9 fftl = 2.0.^ceil(log2(fs/fqLow*6)); fAxis = (0:fftl/2)'/fftl*fs; doubleFAxis = [fAxis(:);fAxis(end-1:-1:2)]; gain = 1*(abs(doubleFAxis)>fqLow); % high pass filter else fftl = 2.0.^ceil(log2(fs/fqLow*6)); fAxis = (0:fftl/2)'/fftl*fs; doubleFAxis = [fAxis(:);fAxis(end-1:-1:2)]; gain = 1*((abs(doubleFAxis)>fqLow) & (abs(doubleFAxis)<fqHigh)); % high pass filter end; switch get(myGUIdata.windowTypePopup,'value') case 1 w = blackman(fftl); case 2 w = hamming(fftl); case 3 w = hanning(fftl); case 4 w = bartlett(fftl); case 5 w = ones(fftl,1); case 6 w = nuttallwin(fftl); otherwise w = blackman(numberOfSamples); end; wFIR = real(fftshift(ifft(gain)).*w); x = myGUIdata.audioData; x = x(max(1,min(length(x),round(fs*xLimit(1)):round(fs*xLimit(end))))); y = fftfilt(wFIR,x); myGUIdata.player = audioplayer(y/max(abs(y))*0.99,fs); guidata(handles.multiScopeMainGUI,myGUIdata); playblocking(myGUIdata.player); end % --- Executes on button press in scrubbingButton. function scrubbingButton_Callback(hObject, eventdata, handles) % hObject handle to scrubbingButton (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 scrubbingButton myGUIdata = guidata(handles.multiScopeMainGUI); switch get(myGUIdata.zoomInTool,'state') case 'on' set(hObject,'value',0) return; end switch get(myGUIdata.zoomOutTool,'state') case 'on' set(hObject,'value',0) return; end switch get(myGUIdata.PanTool,'state') case 'on' set(hObject,'value',0) return; end switch get(myGUIdata.dataCursorTool,'state') case 'on' set(hObject,'value',0) return; end switch get(hObject,'value') case 1 set(myGUIdata.zoomInTool,'enable','off'); set(myGUIdata.zoomOutTool,'enable','off'); set(myGUIdata.PanTool,'enable','off'); set(myGUIdata.dataCursorTool,'enable','off'); set(myGUIdata.withAudioRadioButton,'enable','on'); xlim = get(myGUIdata.sgramAxis,'xlim'); ylim = get(myGUIdata.sgramAxis,'ylim'); ylimShrink = (ylim*0.98+0.02*mean(ylim)); set(myGUIdata.cursorHandle,'xdata',[1 1]*mean(xlim),... 'ydata',ylimShrink,'visible','on'); set(myGUIdata.multiScopeMainGUI,'WindowButtonMotionFcn',@windowMotionFcnForManipulation); set(myGUIdata.multiScopeMainGUI,'WindowButtonUpFcn',@windowButtonUpFcnForManipulation); set(handles.cursorHandle,'ButtonDownFcn',@sgramCursorButtonDownFCN); myGUIdata.initializeScrubbing = 1; myGUIdata.pointerMode = 'dragging'; guidata(handles.multiScopeMainGUI,myGUIdata); windowMotionFcnForManipulation(handles.multiScopeMainGUI,eventdata) myGUIdata.pointerMode = 'normal'; guidata(handles.multiScopeMainGUI,myGUIdata); case 0 set(myGUIdata.zoomInTool,'enable','on'); set(myGUIdata.zoomOutTool,'enable','on'); set(myGUIdata.PanTool,'enable','on'); set(myGUIdata.dataCursorTool,'enable','on'); set(myGUIdata.cursorHandle,'visible','off'); set(myGUIdata.withAudioRadioButton,'enable','off'); set(myGUIdata.multiScopeMainGUI,'WindowButtonMotionFcn',''); set(myGUIdata.multiScopeMainGUI,'WindowButtonUpFcn',''); set(handles.cursorHandle,'ButtonDownFcn',''); end; end % ----------------- private event handlers ------------------ function windowMotionFcnForManipulation(src,evnt) myGUIdata = guidata(src); %switch get(myGUIdata.player,'Running') % case 'on' % return; %end; currentPointInSgram = get(myGUIdata.sgramAxis,'currentpoint'); % (1,1): x, (1,2): y xLimSgram = get(myGUIdata.sgramAxis,'xlim'); yLimSgram = get(myGUIdata.sgramAxis,'ylim'); switch myGUIdata.pointerMode case 'normal' set(myGUIdata.cursorFringeHandle,'visible','off'); scrubbKnobPosition = mean(get(myGUIdata.cursorHandle,'xdata')); if (xLimSgram(1)-currentPointInSgram(1,1))*(xLimSgram(2)-currentPointInSgram(1,1)) < 0 && ... (yLimSgram(1)-currentPointInSgram(1,2))*(yLimSgram(2)-currentPointInSgram(1,2)) < 0 % inside sgram proximityWidth = abs(diff(xLimSgram))*0.01; if abs(currentPointInSgram(1,1)-scrubbKnobPosition)<proximityWidth set(gcf,'pointer','hand'); else set(gcf,'pointer','arrow'); end; else set(gcf,'pointer','arrow'); end; case 'dragging' switch myGUIdata.initializeScrubbing case 0 nextPosition = max(xLimSgram(1),min(xLimSgram(2),currentPointInSgram(1,1))); case 1 %nextPosition = mean(xLimSgram); nextPosition = mean(get(myGUIdata.cursorHandle,'xdata')); myGUIdata.initializeScrubbing = 0; guidata(src,myGUIdata) end; set(myGUIdata.cursorHandle,'visible','on'); set(myGUIdata.cursorFringeHandle,'visible','on'); set(myGUIdata.cursorHandle,'xdata',[0 0]+nextPosition); set(myGUIdata.cursotPositionText,'string',['Cursor: ' num2str(nextPosition,'%2.3f') ' s']); myGUIdata.smallviewerWidth = get(myGUIdata.radiobutton10ms,'value')*10+ ... get(myGUIdata.radiobutton30ms,'value')*30+ ... get(myGUIdata.radiobutton100ms,'value')*100+ ... get(myGUIdata.radiobutton300ms,'value')*300; set(myGUIdata.cursorFringeHandle,'xdata',[-0.5 -0.5 0.5 0.5]*myGUIdata.smallviewerWidth/1000+nextPosition); yLimStretch = yLimSgram*1.1-0.05*mean(yLimSgram); set(myGUIdata.cursorFringeHandle,'ydata',[yLimStretch(1) yLimStretch(2) yLimStretch(2) yLimStretch(1)]); numberOfSamples = round(myGUIdata.smallviewerWidth*myGUIdata.samplingFrequency/1000); x = myGUIdata.audioData; fs = myGUIdata.samplingFrequency; visibleIndex = max(1,min(length(x),round(nextPosition*fs+(1:numberOfSamples)'-numberOfSamples/2))); ydata = x(visibleIndex); yMax = max(abs(ydata)); xdata = 1:numberOfSamples; %ydata = tmpAudio(currentPoint-numberOfSamples+1:currentPoint); set(myGUIdata.smallViewerPlotHandle,'xdata',xdata,'ydata',ydata); set(myGUIdata.smallViewerAxis,'xlim',[0 numberOfSamples],'ylim',yMax*[-1 1]); set(myGUIdata.cursorFringeHandle,'userdata',visibleIndex); fftl = 2^ceil(log2(numberOfSamples)); fAxis = (0:fftl-1)/fftl*fs; switch get(myGUIdata.windowTypePopup,'value') case 1 w = blackman(numberOfSamples); case 2 w = hamming(numberOfSamples); case 3 w = hanning(numberOfSamples); case 4 w = bartlett(numberOfSamples); case 5 w = ones(numberOfSamples,1); case 6 w = nuttallwin(numberOfSamples); otherwise w = blackman(numberOfSamples); end; windowView = w*yMax*2-yMax; set(myGUIdata.windowViewHandle,'xdata',xdata,'ydata',windowView); pw = 20*log10(abs(fft(ydata.*w,fftl)/sqrt(sum(w.^2)))); set(myGUIdata.largeViewerPlotHandle,'xdata',fAxis,'ydata',pw); switch get(myGUIdata.axisTypePopup,'value') case 1 set(myGUIdata.largeViewerAxis,'xlim',[10 fs/2],'xscale','log'); case 2 set(myGUIdata.largeViewerAxis,'xlim',[0 fs/2],'xscale','linear'); case 3 set(myGUIdata.largeViewerAxis,'xlim',[0 10000],'xscale','linear'); case 4 set(myGUIdata.largeViewerAxis,'xlim',[0 8000],'xscale','linear'); case 5 set(myGUIdata.largeViewerAxis,'xlim',[0 4000],'xscale','linear'); otherwise set(myGUIdata.largeViewerAxis,'xlim',[10 fs/2],'xscale','log'); end; end; end function windowButtonUpFcnForManipulation(src,evnt) myGUIdata = guidata(src); myGUIdata.pointerMode = 'normal'; set(myGUIdata.cursotPositionText,'visible','off'); set(myGUIdata.cursorFringeHandle,'visible','off'); guidata(src,myGUIdata); end function sgramCursorButtonDownFCN(src,evnt) multiScopeMainGUI = get(src,'userData'); myGUIdata = guidata(multiScopeMainGUI); %disp('cursor was hit!') myGUIdata.pointerMode = 'dragging'; set(myGUIdata.cursotPositionText,'visible','on'); set(myGUIdata.cursorFringeHandle,'visible','on'); guidata(multiScopeMainGUI,myGUIdata); end function sgramCursorButtonMotionFCN(src,evnt) end % --- 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) myGUIdata = guidata(handles.multiScopeMainGUI); set(myGUIdata.cursorFringeHandle,'visible','off') set(myGUIdata.cursorHandle,'visible','off'); set(myGUIdata.zoomInTool,'enable','on'); set(myGUIdata.zoomOutTool,'enable','on'); set(myGUIdata.PanTool,'enable','on'); set(myGUIdata.dataCursorTool,'enable','on'); [file,path] = uigetfile('*.wav','Select sound file'); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 disp('Load is cancelled!'); return; end; end; [x,fs] = audioread([path file]); myGUIdata.audioData = x(:,1); numberOfChannels = size(x,2); set(myGUIdata.channelPopupMenu,'visible','on'); set(myGUIdata.channelPopupMenu,'string',myGUIdata.channelMenuString(1:min(8,numberOfChannels))); myGUIdata.loadedData = x; myGUIdata.samplingFrequency = fs; set(handles.multiScopeMainGUI,'pointer','watch');drawnow sgramStructure = stftSpectrogramStructure(myGUIdata.audioData,myGUIdata.samplingFrequency,15,2,'blackman'); set(myGUIdata.spectrogramHandle,'cdata',max(-80,sgramStructure.dBspectrogram),'visible','on', ... 'xdata',sgramStructure.temporalPositions,'ydata',sgramStructure.frequencyAxis); set(myGUIdata.sgramAxis,'visible','on', ... 'xlim',[sgramStructure.temporalPositions(1) sgramStructure.temporalPositions(end)], ... 'ylim',[sgramStructure.frequencyAxis(1) sgramStructure.frequencyAxis(end)]); set(myGUIdata.wholeViewerAxis,'visible','off'); set(handles.multiScopeMainGUI,'pointer','arrow');drawnow set(myGUIdata.playTFregion,'enable','on'); set(myGUIdata.scrubbingButton,'enable','on','value',0); myGUIdata.liveData = 'no'; guidata(handles.multiScopeMainGUI,myGUIdata); end % --- Executes on selection change in channelPopupMenu. function channelPopupMenu_Callback(hObject, eventdata, handles) % hObject handle to channelPopupMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns channelPopupMenu contents as cell array % contents{get(hObject,'Value')} returns selected item from channelPopupMenu myGUIdata = guidata(handles.multiScopeMainGUI); channelID = get(hObject,'Value'); myGUIdata.audioData = myGUIdata.loadedData(:,channelID); set(handles.multiScopeMainGUI,'pointer','watch');drawnow sgramStructure = stftSpectrogramStructure(myGUIdata.audioData,myGUIdata.samplingFrequency,15,2,'blackman'); set(myGUIdata.spectrogramHandle,'cdata',max(-80,sgramStructure.dBspectrogram),'visible','on', ... 'xdata',sgramStructure.temporalPositions,'ydata',sgramStructure.frequencyAxis); set(myGUIdata.sgramAxis,'visible','on', ... 'xlim',[sgramStructure.temporalPositions(1) sgramStructure.temporalPositions(end)], ... 'ylim',[sgramStructure.frequencyAxis(1) sgramStructure.frequencyAxis(end)]); set(myGUIdata.wholeViewerAxis,'visible','off'); set(handles.multiScopeMainGUI,'pointer','arrow');drawnow set(myGUIdata.playTFregion,'enable','on'); set(myGUIdata.scrubbingButton,'enable','on','value',0); set(myGUIdata.cursorFringeHandle,'visible','off') set(myGUIdata.cursorHandle,'visible','off'); set(myGUIdata.zoomInTool,'enable','on'); set(myGUIdata.zoomOutTool,'enable','on'); set(myGUIdata.PanTool,'enable','on'); set(myGUIdata.dataCursorTool,'enable','on'); myGUIdata.liveData = 'no'; guidata(handles.multiScopeMainGUI,myGUIdata); end % --- Executes during object creation, after setting all properties. function channelPopupMenu_CreateFcn(hObject, eventdata, handles) % hObject handle to channelPopupMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on button press in withAudioRadioButton. function withAudioRadioButton_Callback(hObject, eventdata, handles) % hObject handle to withAudioRadioButton (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 withAudioRadioButton end
github
HidekiKawahara/SparkNG-master
eventScopeR4.m
.m
SparkNG-master/GUI/eventScopeR4.m
30,279
utf_8
460bbfa47cf7a91999ccc691d5a81f61
function varargout = eventScopeR4(varargin) % EVENTSCOPER4 MATLAB code for eventScopeR4.fig % EVENTSCOPER4, by itself, creates a new EVENTSCOPER4 or raises the existing % singleton*. % % H = EVENTSCOPER4 returns the handle to a new EVENTSCOPER4 or the handle to % the existing singleton*. % % EVENTSCOPER4('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in EVENTSCOPER4.M with the given input arguments. % % EVENTSCOPER4('Property','Value',...) creates a new EVENTSCOPER4 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before eventScopeR4_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to eventScopeR4_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 % Sample program for realtime event detection % Designed and coded by Hideki Kawahara % 28/April/2014 % 29/April/2014 slightly cleaned up % 30/April/2014 further cleaning % 02/May/2014 f0 display revision % 31/Aug./2015 machine independent and resizable % % Comment: % Timer structure used in this routine can be a bad practice. % This tool will be redesigned completely. % This work is licensed under the Creative Commons % Attribution 4.0 International License. % To view a copy of this license, visit % http://creativecommons.org/licenses/by/4.0/. % Edit the above text to modify the response to help eventScopeR4 % Last Modified by GUIDE v2.5 02-May-2014 10:27:55 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @eventScopeR4_OpeningFcn, ... 'gui_OutputFcn', @eventScopeR4_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 end % --- Executes just before eventScopeR4 is made visible. function eventScopeR4_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 eventScopeR4 (see VARARGIN) % Choose default command line output for eventScopeR4 handles.output = hObject; myGUIdata = guidata(hObject); myGUIdata.samplingFrequency = 44100; timerEventInterval = 0.050; % in second myGUIdata.timerEventInterval = timerEventInterval; guidata(hObject, myGUIdata); myGUIdata = initializeDisplay(myGUIdata); timer50ms = timer('TimerFcn',@synchDrawGUI, 'Period',timerEventInterval,'ExecutionMode','fixedRate', ... 'userData',handles.eventScopeGUI); myGUIdata.timer50ms = timer50ms; timerForWaveDraw = timer('TimerFcn',@waveDrawServer,'ExecutionMode','singleShot', ... 'userData',handles.eventScopeGUI); myGUIdata.timerForWaveDraw = timerForWaveDraw; %spectrumBarServer timerForSpectrumBar = timer('TimerFcn',@spectrumBarServer,'ExecutionMode','singleShot', ... 'userData',handles.eventScopeGUI); myGUIdata.timerForSpectrumBar = timerForSpectrumBar; timerForKurtosisBar = timer('TimerFcn',@kurtosisBarServer,'ExecutionMode','singleShot', ... 'userData',handles.eventScopeGUI); myGUIdata.timerForKurtosisBar = timerForKurtosisBar; %fineF0Server timerForFineF0 = timer('TimerFcn',@fineF0Server,'ExecutionMode','singleShot', ... 'userData',handles.eventScopeGUI); myGUIdata.timerForFineF0 = timerForFineF0; myGUIdata.recordObj1 = audiorecorder(myGUIdata.samplingFrequency,24,1); set(myGUIdata.recordObj1,'TimerPeriod',0.2); record(myGUIdata.recordObj1); myGUIdata.maxAudioRecorderCount = myGUIdata.maxTargetPoint; myGUIdata.maxLevel = -100; myGUIdata.lastLevel = 0; myGUIdata.lastLastLevel = 0; myGUIdata.jumpLimit = 10; myGUIdata.output = hObject; myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; % Update handles structure guidata(hObject, myGUIdata); myGUIdata = startRealtime(myGUIdata); myGUIdata.startTime = datevec(now); guidata(hObject, myGUIdata); % UIWAIT makes eventScopeR4 wait for user response (see UIRESUME) % uiwait(handles.eventScopeGUI); end % --- private function function myGUIdata = startRealtime(myGUIdata) switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.lastPosition = 1; record(myGUIdata.recordObj1); switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); case 'on' otherwise disp('timer is bloken!'); end set(myGUIdata.periodicHandle,'ydata',myGUIdata.tAxis+NaN); set(myGUIdata.peakyHandle,'ydata',myGUIdata.tAxis+NaN); %myGUIdata.peakyData = myGUIdata.tAxis+NaN; set(myGUIdata.onsetHandle,'ydata',myGUIdata.tAxis+NaN); %myGUIdata.onsetData = myGUIdata.tAxis+NaN; set(myGUIdata.powerHandle,'ydata',myGUIdata.tAxis+NaN); set(myGUIdata.noteHandle,'ydata',myGUIdata.tAxis*0+NaN); set(myGUIdata.stopButton,'enable','on'); set(myGUIdata.startButton,'enable','off'); myGUIdata.countStarted = false; end % --- private function function myGUIdata = initializeDisplay(myGUIdata) axes(myGUIdata.waveformViewerAxis); myGUIdata.viewWidth = 0.035; tx = 0:floor(myGUIdata.samplingFrequency*myGUIdata.viewWidth); myGUIdata.waveHandle = plot(tx,randn(length(tx),1),'linewidth',2); set(gca,'xlim',[tx(1) tx(end)]); axis('off') myGUIdata.maxTargetPoint = 200;%500; %-------------- axes(myGUIdata.spectrumBarAxis); fs = myGUIdata.samplingFrequency; baseChannelFrequency = 20; myGUIdata.centerFrequencyList = baseChannelFrequency*2.0.^(0:1/3:log2(fs/2/baseChannelFrequency*2^(-1/6)))'; myGUIdata.fLow = myGUIdata.centerFrequencyList*2^(-1/6); myGUIdata.fHigh = myGUIdata.centerFrequencyList*2^(1/6); myGUIdata.channelID = 1:length(myGUIdata.centerFrequencyList); myGUIdata.barHandle = bar(myGUIdata.channelID,80*rand(length(myGUIdata.centerFrequencyList),1),'facecolor',[0.3 0.3 1]); myGUIdata.tickList = [20 30 40 50 60 70 80 90 100 200 300 400 500 600 700 800 900 1000 ... 2000 3000 4000 5000 6000 7000 8000 9000 10000]; myGUIdata.tickLabel = {'02';'03';' ';'05';' ';'07';' ';' ';'.1';'.2';'.3';' ';'.5';' ';'.7';' ';' ';'1'; ... '2';'3';' ';'5';' ';'7';' ';' ';'10'}; myGUIdata.tickocation = interp1(myGUIdata.centerFrequencyList,myGUIdata.channelID,myGUIdata.tickList); set(myGUIdata.barHandle,'BarWidth',1); grid on; xlabel('frequency (kHz)'); ylabel('level (dB)'); set(myGUIdata.spectrumBarAxis,'ylim',[0 90]); %hold on;plot([20 fs/2],0*[1 1],'k','linewidth',2);hold off set(myGUIdata.spectrumBarAxis,'xlim',[0.5 myGUIdata.channelID(end)+0.5]); set(myGUIdata.spectrumBarAxis,'xtick',myGUIdata.tickocation,'xtickLabel',myGUIdata.tickLabel); ytick = 0:10:90; ytickLabel = {'-90';'-80';'-70';'-60';'-50';'-40';'-30';'-20';'-10';'0'}; set(myGUIdata.spectrumBarAxis,'ytick',ytick,'ytickLabel',ytickLabel); myGUIdata.windowLength = 0.04; myGUIdata.windowSizeInSample = round(myGUIdata.windowLength*fs); w = blackman(myGUIdata.windowSizeInSample); myGUIdata.window = w/sqrt(sum(w.^2)); myGUIdata.fftl = 2^ceil(log2(myGUIdata.windowSizeInSample)); myGUIdata.fAxis = (0:myGUIdata.fftl-1)'/myGUIdata.fftl*fs; wTmp = real(ifft(abs(fft(w,myGUIdata.fftl)).^2)); fAxisDFT = myGUIdata.fAxis; fAxisDFT(fAxisDFT>fs/2) = fAxisDFT(fAxisDFT>fs/2)-fs; myGUIdata.baseBandLimit = 3000; myGUIdata.shaper = 0.5+0.5*cos(pi*fAxisDFT/myGUIdata.baseBandLimit); myGUIdata.shaper(abs(fAxisDFT)>myGUIdata.baseBandLimit) = 0; %myGUIdata.shaper = myGUIdata.shaper; myGUIdata.lagwindow = (wTmp/wTmp(1)).^(0.8); myGUIdata.lagAxis = (0:myGUIdata.fftl-1)/fs; %-------------------- axes(myGUIdata.parameterViewerAxis); myGUIdata.tAxis = (0:myGUIdata.maxTargetPoint-1)*myGUIdata.timerEventInterval; myGUIdata.periodicHandle = plot(myGUIdata.tAxis,myGUIdata.tAxis*0+1,'color',[0 0.8 0],'linewidth',7); hold on myGUIdata.peakyHandle = plot(myGUIdata.tAxis,myGUIdata.tAxis*0+2,'m','linewidth',7); myGUIdata.onsetHandle = plot(myGUIdata.tAxis,myGUIdata.tAxis*0+1.5,'r','linewidth',7); myGUIdata.powerHandle = plot(myGUIdata.tAxis,myGUIdata.tAxis*0+3,'b','linewidth',2); set(myGUIdata.parameterViewerAxis,'ylim',[0.5 5],'xlim',[0 myGUIdata.tAxis(end)]); set(myGUIdata.parameterViewerAxis,'ytick',[1 1.5 2 3],'ytickLabel',{'periodic';'onset';'peaky';'level'}); set(myGUIdata.parameterViewerAxis,'xticklabel',[]); grid on; hold off; %--------------------- axes(myGUIdata.kurtosisBarAxis); myGUIdata.kurtosisBarHandle = bar(1,3,'m');grid on; myGUIdata.kurtosisLimit = 40; set(myGUIdata.kurtosisBarAxis,'ylim',[1 myGUIdata.kurtosisLimit],'xtick',[]); xlabel('kurtosis') set(myGUIdata.kurtosisBarAxis,'yscale','log'); ytick = [1:10 20:10:100]; ytickLabel = {'1';'2';'3';' ';'5';' ';'7';' ';' ';'10';... '20';'30';'40';'50';' ';' ';' ';' ';'100';}; set(myGUIdata.kurtosisBarAxis,'ytick',ytick,'ytickLabel',ytickLabel); set(myGUIdata.kurtosisBarHandle,'BarWidth',1) w = blackman(31); ww = w/sum(w); ww(16) = ww(16)-1; myGUIdata.kurtosisHPF = -ww; %--------------------- axes(myGUIdata.powerBarAxis); myGUIdata.totalPowerBarHandle = bar(1,-80,'b');grid on; set(myGUIdata.powerBarAxis,'ylim',[0 90],'xtick',[]); xlabel('power'); ylabel('level (dB)') set(myGUIdata.powerBarAxis,'ytick',[0:10:90],'ytickLabel',... {'-90';'-80';'-70';'-60';'-50';'-40';'-30';'-20';'-10';'0'}); set(myGUIdata.totalPowerBarHandle,'BarWidth',1) %--------------------- axes(myGUIdata.periodicityBarAxis); myGUIdata.periodicityBarHandle = bar(1,0.5,'g');grid on; set(myGUIdata.periodicityBarAxis,'ylim',[0 1],'xtick',[],'ytick',0:0.1:1); xlabel('max.corr.'); set(myGUIdata.periodicityBarHandle,'BarWidth',1) %--------------------- %noteAxis myGUIdata.noteID = (-7:27+7)'; %110*2.0.^((-2:27)/12); myGUIdata.noteName = {'D2';' ';'E2';'F2';' ';'G2';' ';'A2';' ';'H2';'C3';' ';'D3';' ';'E3';'F3';' ';'G3';' ';'A3'; ... ' ';'H3';'C4';' ';'D4';' ';'E4';' ';'F4';'G4';' ';'A4';' ';'H4';'C5' ... ;' ';'D5';' ';'E5';'F5';' ';'G5'}; axes(myGUIdata.noteAxis); myGUIdata = initializeForFineF0(myGUIdata); hold on; myGUIdata.SecondNoteHandle = plot(myGUIdata.tAxis,myGUIdata.tAxis*0,'s','markersize',5, ... 'markerfacecolor',[0.5 0.8 0.5],'markeredgecolor',[0.5 0.8 0.5]); myGUIdata.noteHandle = plot(myGUIdata.tAxis,myGUIdata.tAxis*0,'s','markersize',7, ... 'markerfacecolor',[0 0.8 0],'markeredgecolor',[0 0.8 0]); frequencyTick = [40 50 60 70 80 90 100 150 200 300 400 500 600 700 800 900 1000]; frequencyBase = 10:10:2000; hold off myGUIdata.freqtickLocation = interp1(frequencyBase,12*log2(frequencyBase/110),frequencyTick); myGUIdata.freqTickLabel = {'40';'50';'60';'70';'80';'90';'100';'150';'200';'300';'400';'500';'600';'700';'800';'900';'1000';}; set(myGUIdata.noteAxis,'ytick',myGUIdata.noteID,'ytickLabel',myGUIdata.noteName); set(myGUIdata.SecondNoteHandle,'ydata',myGUIdata.tAxis*0+NaN); set(myGUIdata.noteHandle,'ydata',myGUIdata.tAxis*0+NaN); grid on; set(myGUIdata.noteAxis,'ylim',[myGUIdata.noteID(1) myGUIdata.noteID(end)+1],'xlim',[0 myGUIdata.tAxis(end)]); %--------------------- axes(myGUIdata.colorPadAxis); tcmx = zeros(30,10,3); tcmx(4:27,3:8,:) = 1; myGUIdata.baseTrueColor = tcmx; myGUIdata.colorPadHandle = image(tcmx); axis('off') set(myGUIdata.fpsText,'string','20.0 fps'); %--------------------- set(myGUIdata.noteRadioButton,'userdata',myGUIdata,'enable','on'); set(myGUIdata.freqRadioButton,'userdata',myGUIdata,'enable','on'); set(myGUIdata.axisModePanel,'userdata',myGUIdata,'SelectionChangeFcn',@modeRadioButterServer); set(myGUIdata.saveFileButton,'enable','off'); end function myGUIdata = initializeForFineF0(myGUIdata) fs = myGUIdata.samplingFrequency; myGUIdata.fineFrameShift = 0.010; myGUIdata.fineTimeAxis = 0:myGUIdata.fineFrameShift:myGUIdata.tAxis(end); myGUIdata.fineF0Handle = plot(myGUIdata.fineTimeAxis,myGUIdata.fineTimeAxis*0,'s','markersize',5, ... 'markerfacecolor',[0 0.7 0],'markeredgecolor',[0 0.7 0]); hold on %myGUIdata.fine2ndF0Handle = plot(myGUIdata.fineTimeAxis,myGUIdata.fineTimeAxis*0,'s','markersize',3, ... % 'markerfacecolor',[0.4 0.9 0.4],'markeredgecolor',[0.4 0.9 0.4]); hold off set(myGUIdata.fineF0Handle,'ydata',myGUIdata.fineTimeAxis*0+NaN); %set(myGUIdata.fine2ndF0Handle,'ydata',myGUIdata.fineTimeAxis*0+NaN); frameShift = 0.010; % 10ms frameLength = 0.046; % 40ms narrowWindow = 0.004; % 10ms fsb4 = fs/4; windowLengthInSample = round(frameLength*fsb4/2)*2+1; % always odd number baseIndex = (-round(frameLength*fsb4/2):round(frameLength*fsb4/2))'; fftl = 2^ceil(log2(windowLengthInSample)); w = hanning(windowLengthInSample); x = randn(round(myGUIdata.tAxis(end)*fs),1); %xb4 = x(1:4:end); narrowWindow = hanning(round(narrowWindow*fsb4/2)*2+1); lagNarrowWindow = conv(narrowWindow,narrowWindow); halfNarrorLength = round((length(lagNarrowWindow)-1)/2); lagWindowForDFT = zeros(fftl,1); lagWindowForDFT(1:halfNarrorLength+1) = lagNarrowWindow(halfNarrorLength+1:end); lagWindowForDFT(fftl:-1:fftl-halfNarrorLength+1) = lagNarrowWindow(halfNarrorLength+2:end); fx = (0:fftl-1)/fftl*fsb4; fx(fx>fsb4/2) = fx(fx>fsb4/2)-fsb4; hanningLPF = (0.5+0.5*cos(pi*fx(:)/2000)).^2; hanningLPF(abs(fx)>2000) = 0; wConv = conv(w,w); [centerValue,centerIndex] = max(wConv); mainLagWindow = zeros(fftl,1); mainLagWindow(1:fftl/2) = wConv(centerIndex+(1:fftl/2)-1); mainLagWindow(fftl:-1:fftl/2+1) = wConv(centerIndex+(1:fftl/2)); mainLagWindow = mainLagWindow.^0.7; % ad hoc mainLagWindow(1:10) = mainLagWindow(1:10)*10; mainLagWindow(end:-1:end-9) = mainLagWindow(end:-1:end-9)*10; tickLocations = 0:frameShift:(length(x)-1)/fs; normalizedAcGram = zeros(fftl,length(tickLocations)); %-------- myGUIdata.frameShiftb4 = frameShift; myGUIdata.frameLengthb4 = frameLength; myGUIdata.windowLengthInSampleb4 = windowLengthInSample; myGUIdata.fsb4 = fsb4; myGUIdata.baseIndexb4 = baseIndex; myGUIdata.tickLocationsb4 = tickLocations; myGUIdata.tickIndexb4 = (1:length(tickLocations))'; myGUIdata.fftlb4 = fftl; myGUIdata.wb4 = w; myGUIdata.hanningLPFb4 = hanningLPF; myGUIdata.lagWindowForDFTb4 = lagWindowForDFT; myGUIdata.mainLagWindowb4 = mainLagWindow; myGUIdata.normalizedAcGram = normalizedAcGram; myGUIdata.countStarted = false; %myGUIdata.tickB4ID = 0; %myGUIdata end % xSegment = xb4(max(1,min(length(xb4),baseIndex+round(tickLocations(ii)*fsb4)))); % pw = abs(fft(xSegment.*w,fftl)).^2; % ac = real(ifft(pw)); % normalizedPw = hanningLPF.*pw./fft(ac.*lagWindowForDFT); % normalizedAc = real(ifft(normalizedPw))./mainLagWindow; % mormalizedAcGram(:,ii) = normalizedAc/normalizedAc(1)/10; function fineF0Server(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); fs = myGUIdata.samplingFrequency; bias = round(myGUIdata.frameLengthb4/2*myGUIdata.fsb4); %myGUIdata.tickB4ID = myGUIdata.tickB4ID+1; %x = myGUIdata.tmpAudio; tmpIndex = length(myGUIdata.tmpAudio)-(round(myGUIdata.frameLengthb4*fs)+1+round(myGUIdata.frameShiftb4*fs*5)):length(myGUIdata.tmpAudio); if length(tmpIndex) > myGUIdata.windowLengthInSampleb4 x = myGUIdata.tmpAudio(max(1,tmpIndex)); currentIndex = myGUIdata.maxTargetPoint-myGUIdata.audioRecorderCount; if currentIndex > 0 xb4 = x(1:4:end); t0 = 1/myGUIdata.fsb4; ydata = get(myGUIdata.fineF0Handle,'ydata'); %ydata2nd = get(myGUIdata.fine2ndF0Handle,'ydata'); if 1 == 1 for ii = 1:5 xSegment = xb4(max(1,min(length(xb4),bias+myGUIdata.baseIndexb4+round(myGUIdata.frameShiftb4*(ii-1)*myGUIdata.fsb4)))); pw = abs(fft(xSegment.*myGUIdata.wb4,myGUIdata.fftlb4)).^2; ac = real(ifft(pw)); normalizedPw = myGUIdata.hanningLPFb4.*pw./fft(ac.*myGUIdata.lagWindowForDFTb4); normalizedAc = real(ifft(normalizedPw))./myGUIdata.mainLagWindowb4; normalizedAc = normalizedAc/normalizedAc(1)/10; %[peakLevel,maxpos] = max(normalizedAc(1:150)); %bestLag = (peakIdx-1)*t0; [peakLevel,maxpos] = max(normalizedAc(1:150)); maxpos = max(2,maxpos); bestLag = (0.5*(normalizedAc(maxpos-1)-normalizedAc(maxpos+1))/ ... (normalizedAc(maxpos-1)+normalizedAc(maxpos+1)-2*normalizedAc(maxpos))+maxpos-1)*t0; notePosition = max(-7,min(myGUIdata.noteID(end)+1,(12*log2(1/bestLag/110)))); if peakLevel > 0.55 ydata(min(length(ydata),ii+(currentIndex-1)*5)) = notePosition; else %ydata2nd(min(length(ydata),ii+(currentIndex-1)*5)) = notePosition; end; end; %disp(num2str(peakLevel)) set(myGUIdata.fineF0Handle,'ydata',ydata); %set(myGUIdata.fine2ndF0Handle,'ydata',ydata2nd); end; end; end; end function modeRadioButterServer(obj, event, string_arg) myGUIdata = get(obj,'userdata'); %disp('selection changed'); switch get(myGUIdata.noteRadioButton,'value') case 1 set(myGUIdata.noteAxis,'ytick',myGUIdata.noteID,'ytickLabel',myGUIdata.noteName); otherwise set(myGUIdata.noteAxis,'ytick',myGUIdata.freqtickLocation,'ytickLabel',myGUIdata.freqTickLabel); end end % --- private function function synchDrawGUI(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); fftl = myGUIdata.fftl; numberOfSamples = fftl*6; if get(myGUIdata.recordObj1,'TotalSamples') > numberOfSamples myGUIdata.tmpAudio = getaudiodata(myGUIdata.recordObj1); guidata(handleForTimer,myGUIdata); switch get(myGUIdata.timerForWaveDraw,'running') case 'off' start(myGUIdata.timerForWaveDraw); end; switch get(myGUIdata.timerForKurtosisBar,'running') case 'off' start(myGUIdata.timerForKurtosisBar); end; %timerForFineF0 switch get(myGUIdata.timerForFineF0,'running') case 'off' start(myGUIdata.timerForFineF0); end; switch get(myGUIdata.timerForSpectrumBar,'running') case 'off' start(myGUIdata.timerForSpectrumBar); end; if myGUIdata.audioRecorderCount < 0 fps = (myGUIdata.maxAudioRecorderCount+1)/etime(datevec(now),myGUIdata.startTime); switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end stop(myGUIdata.recordObj1); set(myGUIdata.fpsText,'string',[num2str(fps,'%02.1f') ' fps']); set(myGUIdata.periodicHandle,'ydata',myGUIdata.tAxis+NaN); set(myGUIdata.peakyHandle,'ydata',myGUIdata.tAxis+NaN); %myGUIdata.peakyData = myGUIdata.tAxis+NaN; set(myGUIdata.onsetHandle,'ydata',myGUIdata.tAxis+NaN); %myGUIdata.onsetData = myGUIdata.tAxis+NaN; set(myGUIdata.powerHandle,'ydata',myGUIdata.tAxis+NaN); set(myGUIdata.noteHandle,'ydata',myGUIdata.tAxis*0+NaN); set(myGUIdata.fineF0Handle,'ydata',myGUIdata.fineTimeAxis*0+NaN); %set(myGUIdata.fine2ndF0Handle,'ydata',myGUIdata.fineTimeAxis*0+NaN); record(myGUIdata.recordObj1); myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); end myGUIdata.countStarted = false; else if ~myGUIdata.countStarted myGUIdata.countStarted = true; myGUIdata.startTime = datevec(now); end; %set(myGUIdata.peakyHandle,'ydata',myGUIdata.peakyData); %set(myGUIdata.onsetHandle,'ydata',myGUIdata.onsetData); set(myGUIdata.countText,'String',num2str(myGUIdata.audioRecorderCount)); myGUIdata.audioRecorderCount = myGUIdata.audioRecorderCount-1; x = myGUIdata.tmpAudio(end-myGUIdata.windowSizeInSample+1:end); rawPower = abs(fft(x.*myGUIdata.window,myGUIdata.fftl)).^2/myGUIdata.fftl; %cumulatedPower = cumsum(rawPmower); myGUIdata.lastLastLevel = myGUIdata.lastLevel; myGUIdata.lastLevel = 10*log10(sum(rawPower)); end; end; %drawnow peakyData = get(myGUIdata.peakyHandle,'ydata'); onsetData = get(myGUIdata.onsetHandle,'ydata'); guidata(handleForTimer,myGUIdata); %drawnow; end function waveDrawServer(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); xdata = get(myGUIdata.waveHandle,'xdata'); ydata = myGUIdata.tmpAudio(end-length(xdata)+1:end); set(myGUIdata.waveHandle,'ydata',ydata); set(myGUIdata.waveformViewerAxis,'ylim',max(abs(ydata))*[-1 1]); end function kurtosisBarServer(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); x = myGUIdata.tmpAudio(end-(myGUIdata.windowSizeInSample+length(myGUIdata.kurtosisHPF))+1:end); xx = fftfilt(myGUIdata.kurtosisHPF,x); xx = xx(length(myGUIdata.kurtosisHPF):end); kutrosisValue = mean(xx.^4)/mean(xx.^2)^2; set(myGUIdata.kurtosisBarHandle,'ydata',max(0,min(myGUIdata.kurtosisLimit,kutrosisValue))); ydataPeaky = get(myGUIdata.peakyHandle,'ydata'); currentIndex = myGUIdata.maxTargetPoint-myGUIdata.audioRecorderCount; if kutrosisValue > 5.9; % p < 10^(-4) for exp. dist (3.7 % p < 10^(-5) for normal distribution) ydataPeaky(max(1,min(myGUIdata.maxTargetPoint,currentIndex))) = 2; %myGUIdata.peakyData(max(1,min(myGUIdata.maxTargetPoint,currentIndex))) = 2; set(myGUIdata.kurtosisBarHandle,'facecolor','m'); set(myGUIdata.peakyHandle,'ydata',ydataPeaky); else set(myGUIdata.kurtosisBarHandle,'facecolor',[0.6 0 0.6]); end; set(myGUIdata.totalPowerBarHandle,'ydata',max(0,min(90,90+20*log10(std(x))))); %guidata(handleForTimer,myGUIdata); end function spectrumBarServer(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); x = myGUIdata.tmpAudio(end-myGUIdata.windowSizeInSample+1:end); rawPower = abs(fft(x.*myGUIdata.window,myGUIdata.fftl)).^2/myGUIdata.fftl; cumulatedPower = cumsum(rawPower); powerH = interp1(myGUIdata.fAxis,cumulatedPower,myGUIdata.fHigh); powerL = interp1(myGUIdata.fAxis,cumulatedPower,myGUIdata.fLow); bandPower = (powerH-powerL)/cumulatedPower(end)*2*std(x)^2; ydata = max(0,min(90,90+10*log10(bandPower))); set(myGUIdata.barHandle,'ydata',ydata); ydataPower = get(myGUIdata.powerHandle,'ydata'); currentIndex = myGUIdata.maxTargetPoint-myGUIdata.audioRecorderCount; ydataPower(max(1,min(myGUIdata.maxTargetPoint,currentIndex))) = ... 3+max(0,min(2,1.5+2.5/80*10*log10(cumulatedPower(end)))); set(myGUIdata.powerHandle,'ydata',ydataPower); if myGUIdata.lastLevel+myGUIdata.jumpLimit < 10*log10(cumulatedPower(end)) ydataOnset = get(myGUIdata.onsetHandle,'ydata'); ydataOnset(max(1,min(myGUIdata.maxTargetPoint,currentIndex))) = 1.5; set(myGUIdata.totalPowerBarHandle,'facecolor','r'); set(myGUIdata.onsetHandle,'ydata',ydataOnset); elseif (myGUIdata.lastLastLevel+myGUIdata.jumpLimit < 10*log10(cumulatedPower(end))) %ydataOnset = get(myGUIdata.onsetHandle,'ydata'); %ydataOnset = myGUIdata.onsetData; ydataOnset = get(myGUIdata.onsetHandle,'ydata'); %if isnan(ydataOnset(max(1,min(myGUIdata.maxTargetPoint,currentIndex-1)))) ydataOnset(max(1,min(myGUIdata.maxTargetPoint,currentIndex-1))) = 1.5; %myGUIdata.onsetData = ydataOnset; set(myGUIdata.totalPowerBarHandle,'facecolor','r'); set(myGUIdata.onsetHandle,'ydata',ydataOnset); %end; else set(myGUIdata.totalPowerBarHandle,'facecolor','b'); end; modifiedAutoCorrelation = real(ifft(rawPower.*myGUIdata.shaper)); modifiedAutoCorrelation = modifiedAutoCorrelation/modifiedAutoCorrelation(1); modifiedAutoCorrelation = modifiedAutoCorrelation./myGUIdata.lagwindow; [maxModifiedAutoCorrelation,lagIDx] = max(modifiedAutoCorrelation((myGUIdata.lagAxis>0.0005) & (myGUIdata.lagAxis<0.014))); %truncatedLag = myGUIdata.lagAxis((myGUIdata.lagAxis>0.0005) & (myGUIdata.lagAxis<0.014)); %bestLag = truncatedLag(lagIDx); set(myGUIdata.periodicityBarHandle,'ydata',maxModifiedAutoCorrelation); if maxModifiedAutoCorrelation > 0.8%0.75 ydataPeriod = get(myGUIdata.periodicHandle,'ydata'); ydataPeriod(max(1,min(myGUIdata.maxTargetPoint,currentIndex))) = 1; set(myGUIdata.periodicHandle,'ydata',ydataPeriod); %notePosition = max(-7,min(myGUIdata.noteID(end)+1,(12*log2(1/bestLag/110)))); %ydataNote = get(myGUIdata.noteHandle,'ydata'); %if notePosition < myGUIdata.noteID(end)+1 % ydataNote(max(1,min(myGUIdata.maxTargetPoint,currentIndex))) = notePosition; %end; %set(myGUIdata.noteHandle,'ydata',ydataNote); set(myGUIdata.periodicityBarHandle,'facecolor','g'); else set(myGUIdata.periodicityBarHandle,'facecolor',[0 0.6 0]); end; cdata = myGUIdata.baseTrueColor; rgbList = [sum(bandPower(1:20)) sum(bandPower(18:26)) sum(bandPower(25:end))]; rgbList = rgbList/max(rgbList); cdata(:,:,1) = cdata(:,:,1)*rgbList(1); cdata(:,:,2) = cdata(:,:,2)*rgbList(2); cdata(:,:,3) = cdata(:,:,3)*rgbList(3); set(myGUIdata.colorPadHandle,'cdata',cdata); if 1 == 2 myGUIdata.lastLastLevel = myGUIdata.lastLevel; myGUIdata.lastLevel = 10*log10(cumulatedPower(end)); guidata(handleForTimer,myGUIdata); end; end % --- Outputs from this function are returned to the command line. function varargout = eventScopeR4_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; end % --- Executes on button press in startButton. function startButton_Callback(hObject, eventdata, handles) % hObject handle to startButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.eventScopeGUI); myGUIdata = startRealtime(myGUIdata); set(myGUIdata.saveFileButton,'enable','off'); guidata(hObject, myGUIdata); end % --- Executes on button press in stopButton. function stopButton_Callback(hObject, eventdata, handles) % hObject handle to stopButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.eventScopeGUI); %disp('timer ends') switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) end; stop(myGUIdata.recordObj1); set(myGUIdata.stopButton,'enable','off'); set(myGUIdata.startButton,'enable','on'); set(myGUIdata.saveFileButton,'enable','on'); end % --- Executes on button press in quitButton. function quitButton_Callback(hObject, eventdata, handles) % hObject handle to quitButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.eventScopeGUI); %disp('timer ends') switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) end; stop(myGUIdata.recordObj1); delete(myGUIdata.timer50ms); delete(myGUIdata.recordObj1); delete(myGUIdata.timerForWaveDraw); delete(myGUIdata.timerForSpectrumBar); delete(myGUIdata.timerForKurtosisBar); delete(myGUIdata.timerForFineF0); close(handles.eventScopeGUI); end % --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over noteRadioButton. function noteRadioButton_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to noteRadioButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) end % --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over freqRadioButton. function freqRadioButton_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to freqRadioButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) end % --- Executes during object creation, after setting all properties. function axisModePanel_CreateFcn(hObject, eventdata, handles) % hObject handle to axisModePanel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called end % -------------------------------------------------------------------- function axisModePanel_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to axisModePanel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = get(hObject,'userdata'); %disp('axisModePanel was hit'); switch get(myGUIdata.freqRadioButton,'value') case 1 set(myGUIdata.noteAxis,'ytick',myGUIdata.freqtickLocation,'ytickLabel',myGUIdata.freqTickLabel); otherwise set(myGUIdata.noteAxis,'ytick',myGUIdata.noteID,'ytickLabel',myGUIdata.noteName); end; end % --- Executes on button press in saveFileButton. function saveFileButton_Callback(hObject, eventdata, handles) % hObject handle to saveFileButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.eventScopeGUI); outFileName = ['eventData' datestr(now,30) '.wav']; [file,path] = uiputfile(outFileName,'Save the captured data'); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 %okInd = 0; disp('Save is cancelled!'); return; end; end; audiowrite([path file],myGUIdata.tmpAudio,myGUIdata.samplingFrequency); end
github
HidekiKawahara/SparkNG-master
vtlDisplay.m
.m
SparkNG-master/GUI/vtlDisplay.m
11,245
utf_8
07cc1bbf3f4ed0cd5105cd13546798c0
function varargout = vtlDisplay(varargin) % VTLDISPLAY MATLAB code for vtlDisplay.fig % VTLDISPLAY, by itself, creates a new VTLDISPLAY or raises the existing % singleton*. % % H = VTLDISPLAY returns the handle to a new VTLDISPLAY or the handle to % the existing singleton*. % % VTLDISPLAY('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in VTLDISPLAY.M with the given input arguments. % % VTLDISPLAY('Property','Value',...) creates a new VTLDISPLAY or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before vtlDisplay_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to vtlDisplay_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 % This work is licensed under the Creative Commons % Attribution 4.0 International License. % To view a copy of this license, visit % http://creativecommons.org/licenses/by/4.0/. % Release note % Realtime vocal tract log area function display % by Hideki Kawahara % 17/Jan./2014 % 26/Jan./2014 frame rate monirot % 31/Aug./2015 machine independence and resizable GUI % Edit the above text to modify the response to help vtlDisplay % Last Modified by GUIDE v2.5 16-Jan-2014 23:57:35 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @vtlDisplay_OpeningFcn, ... 'gui_OutputFcn', @vtlDisplay_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 end % --- Executes just before vtlDisplay is made visible. function vtlDisplay_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 vtlDisplay (see VARARGIN) % Choose default command line output for vtlDisplay handles.output = hObject; % Update handles structure guidata(hObject, handles); delete(timerfindall); initializeDisplay(handles); myGUIdata = guidata(handles.vtVisualizeGUI); timerEventInterval = 0.010; % in second timer50ms = timer('TimerFcn',@synchDrawGUI, 'Period',timerEventInterval,'ExecutionMode','fixedRate', ... 'userData',handles.vtVisualizeGUI); %handleForTimer = handles.multiScopeMainGUI; % global myGUIdata.timer50ms = timer50ms; myGUIdata.smallviewerWidth = 30; % 30 ms is defaule myGUIdata.recordObj1 = audiorecorder(myGUIdata.samplingFrequency,24,1); set(myGUIdata.recordObj1,'TimerPeriod',0.2); record(myGUIdata.recordObj1) myGUIdata.maxAudioRecorderCount = 1000; myGUIdata.maxLevel = -100; myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.startTic = tic; myGUIdata.lastTime = toc(myGUIdata.startTic); %myGUIdata.displayTypeList = myGUIdata.displayTypeList(1:2); guidata(handles.vtVisualizeGUI,myGUIdata); startButton_Callback(hObject, eventdata, handles) % UIWAIT makes vtlDisplay wait for user response (see UIRESUME) % uiwait(handles.vtVisualizeGUI); end function initializeDisplay(handles) myGUIdata = guidata(handles.vtVisualizeGUI); myGUIdata.samplingFrequency = 8000; % in Hz myGUIdata.windowLength = 0.08; % in second myGUIdata.windowLengthInSamples = round(myGUIdata.windowLength*myGUIdata.samplingFrequency/2)*2+1; myGUIdata.fftl = 2.0^ceil(log2(myGUIdata.windowLengthInSamples)); axes(handles.spectrumDisplayAxis); w = blackman(myGUIdata.windowLengthInSamples); w = w/sqrt(sum(w.^2)); myGUIdata.window = w; fs = myGUIdata.samplingFrequency; myGUIdata.displayFrequencyAxis = (0:myGUIdata.fftl-1)/myGUIdata.fftl*fs; tt = (1:myGUIdata.windowLengthInSamples)'/fs; %x = randn(myGUIdata.windowLengthInSamples,1); x = sin(2*pi*440*tt); pw = 10*log10(abs(fft(x.*w,myGUIdata.fftl)).^2/myGUIdata.fftl); myGUIdata.spectrumPlotHandle = plot(myGUIdata.displayFrequencyAxis,pw); hold on; myGUIdata.spectrumLPCPlotHandle = plot(myGUIdata.displayFrequencyAxis,pw,'r', ... 'linewidth',2);grid on; %set(handles.spectrumDisplayAxis,'xlim',[0 fs/2]); axis([0 fs/2 -110 0]); set(gca,'fontsize',14,'linewidth',2); xlabel('frequency (Hz)') ylabel('level (dB rel. MSB)'); legend('power spectrum','14th order LPC'); set(handles.spectrumDisplayAxis,'HandleVisibility','off'); axes(handles.VTDisplayAxis); logAreaFunction = [4 3.7 4 2.7 2.2 1.9 1.9 1.5 0.8 0]; locationList = [1 3 5 7 9 11 13 15 17 19]; displayLocationList = 0:0.1:21; displayLogArea = interp1(locationList,logAreaFunction,displayLocationList,'nearest','extrap'); myGUIdata.logAreaHandle = plot(displayLocationList,displayLogArea-mean(displayLogArea),'linewidth',4); hold on; plot(displayLocationList,0*displayLogArea,'linewidth',1); for ii = 0:20 magCoeff = 1; if rem(ii,5) == 0 magCoeff = 2; text(ii,-0.7,num2str(ii),'fontsize',16,'HorizontalAlignment','center'); end; if rem(ii,10) == 0 magCoeff = 3; end; plot([ii ii],[-0.1 0.1]*magCoeff); end; axis([-0.5 20.5 -5 5]); axis off set(handles.VTDisplayAxis,'HandleVisibility','off'); axes(handles.tract3DAxis); crossSection = [0.2803; ... 0.6663; ... 0.5118; ... 0.3167; ... 0.1759; ... 0.1534; ... 0.1565; ... 0.1519; ... 0.0878; ... 0.0737]; [X,Y,Z] = cylinder(crossSection,40); myGUIdata.tract3D = surf(Z,Y,X); view(-26,12); axis([0 1 -1 1 -1 1]); axis off; axis('vis3d'); rotate3d on; guidata(handles.vtVisualizeGUI,myGUIdata); end function synchDrawGUI(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); w = myGUIdata.window; numberOfSamples = length(w); if get(myGUIdata.recordObj1,'TotalSamples') > numberOfSamples tmpAudio = getaudiodata(myGUIdata.recordObj1); currentPoint = length(tmpAudio); x = tmpAudio(currentPoint-numberOfSamples+1:currentPoint); %x = [0;diff(x)]; pw = abs(fft(x.*w,myGUIdata.fftl)).^2/myGUIdata.fftl; pwdB = 10*log10(pw); set(myGUIdata.spectrumPlotHandle,'ydata',pwdB); ac = real(ifft(pw)); [alp,err,k] = levinson(ac,14); env = 1.0./abs(fft(alp,myGUIdata.fftl)).^2; env = sum(pw)*env/sum(env); envDB = 10*log10(env); set(myGUIdata.spectrumLPCPlotHandle,'ydata',envDB); logArea = signal2logArea(x); nSection = length(logArea); locationList = (1:nSection)*2-1; xdata = get(myGUIdata.logAreaHandle,'xdata'); displayLogArea = interp1(locationList,logArea,xdata,'nearest','extrap'); set(myGUIdata.logAreaHandle,'ydata',displayLogArea-mean(displayLogArea)); [X,Y,Z] = cylinder(tubeDisplay(logArea),40); set(myGUIdata.tract3D,'xdata',Z,'ydata',Y,'zdata',X); if myGUIdata.audioRecorderCount < 0 switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end stop(myGUIdata.recordObj1); record(myGUIdata.recordObj1); myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; currentTime = toc(myGUIdata.startTic); framePerSecond = 1.0./(currentTime-myGUIdata.lastTime)*1000; set(myGUIdata.fpsDisplayText,'String',[num2str(framePerSecond,'%3.3f') ' fps']); myGUIdata.lastTime = currentTime; switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); end else set(myGUIdata.countDownText,'String',num2str(myGUIdata.audioRecorderCount)); myGUIdata.audioRecorderCount = myGUIdata.audioRecorderCount-1; end; else %disp(['Recorded data is not enough! Skipping this interruption....at ' datestr(now,30)]); set(myGUIdata.countDownText,'String','Initilizing...'); end; guidata(myGUIdata.vtVisualizeGUI,myGUIdata); end % --- Outputs from this function are returned to the command line. function varargout = vtlDisplay_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; end % --- Executes on button press in startButton. function startButton_Callback(hObject, eventdata, handles) % hObject handle to startButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.vtVisualizeGUI); myGUIdata.startTic = tic; myGUIdata.lastTime = toc(myGUIdata.startTic); set(myGUIdata.startButton,'enable','off'); set(myGUIdata.stopButton,'enable','on'); switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.lastPosition = 1; record(myGUIdata.recordObj1); switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); case 'on' otherwise disp('timer is bloken!'); end guidata(handles.vtVisualizeGUI,myGUIdata); end % --- Executes on button press in stopButton. function stopButton_Callback(hObject, eventdata, handles) % hObject handle to stopButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.vtVisualizeGUI); myGUIdata.audioData = getaudiodata(myGUIdata.recordObj1); currentTime = toc(myGUIdata.startTic); framePerSecond = 1.0./(currentTime-myGUIdata.lastTime)*(1000-myGUIdata.audioRecorderCount); set(myGUIdata.fpsDisplayText,'String',[num2str(framePerSecond,'%3.3f') ' fps']); %disp('timer ends') %set(myGUIdata.startButton,'enable','off'); set(myGUIdata.startButton,'enable','on'); set(myGUIdata.stopButton,'enable','off'); switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) case 'off' otherwise disp('timer is bloken!'); end; stop(myGUIdata.recordObj1); guidata(handles.vtVisualizeGUI,myGUIdata); end % --- Executes on button press in quitButton. function quitButton_Callback(hObject, eventdata, handles) % hObject handle to quitButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.vtVisualizeGUI); %disp('timer ends') switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) end; stop(myGUIdata.recordObj1); delete(myGUIdata.timer50ms); delete(myGUIdata.recordObj1); close(handles.vtVisualizeGUI); end
github
HidekiKawahara/SparkNG-master
lfModelDesignerX.m
.m
SparkNG-master/GUI/lfModelDesignerX.m
40,031
utf_8
1e06bc59b6ccf1ee3fbee8cafead9b73
function varargout = lfModelDesignerX(varargin) % LFMODELDESIGNERX MATLAB code for lfModelDesignerX.fig % LFMODELDESIGNERX, by itself, creates a new LFMODELDESIGNERX or raises the existing % singleton*. % % H = LFMODELDESIGNERX returns the handle to a new LFMODELDESIGNERX or the handle to % the existing singleton*. % % LFMODELDESIGNERX('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LFMODELDESIGNERX.M with the given input arguments. % % LFMODELDESIGNERX('Property','Value',...) creates a new LFMODELDESIGNERX or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before lfModelDesignerX_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to lfModelDesignerX_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 lfModelDesignerX % Originally designed and coded by Hideki Kawahara % 10/July/2015 first version % 29/July/2015 integrated with VT shape to sound tool % 01/Aug./2015 bug fixed version % 15/Nov./2015 recording data compatibility % Last Modified by GUIDE v2.5 30-Jul-2015 18:54:03 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @lfModelDesignerX_OpeningFcn, ... 'gui_OutputFcn', @lfModelDesignerX_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 end % --- Executes just before lfModelDesignerX is made visible. function lfModelDesignerX_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 lfModelDesignerX (see VARARGIN) % Choose default command line output for lfModelDesignerX handles.output = hObject; %disp(['vargin counts of lfModelDesignerX:' num2str(nargin)]); %celldisp(varargin); handles.variableF0 = 'on'; handles.sourceModel = 'LF'; % other model is 'FjLj' if nargin == 4 && ishandle(varargin{1}) && ishghandle(varargin{1}) parentUserData = guidata(varargin{1}); if isfield(parentUserData,'vtTester') handles.parentUserData = parentUserData; %disp('called from the vt tool.'); if isfield(parentUserData,'variableF0') switch parentUserData.variableF0 case 'on' handles.variableF0 = 'on'; otherwise handles.variableF0 = 'off'; end else handles.variableF0 = 'off'; end if isfield(parentUserData,'sourceModel') handles.sourceModel = parentUserData.sourceModel; end end end %hObject %handles handles = initializeGraphics(handles); %handles % Update handles structure guidata(hObject, handles); % UIWAIT makes lfModelDesignerX wait for user response (see UIRESUME) % uiwait(handles.LFModelDesignerFigure); end % --- Outputs from this function are returned to the command line. function varargout = lfModelDesignerX_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; end %--- private --- function updatedHandles = initializeGraphics(handles) updatedHandles = handles; %--- L-F parameter initial value LFparameters = struct; %LFparameters.voiceQuality = 'breathy'; voiceQuality = 'modal'; fsPlot = 1000; LFparameters.timeForDisplay = -0.2:1/fsPlot:1.2; switch voiceQuality case 'modal' LFparameters.tp = 0.4134; LFparameters.te = 0.5530; LFparameters.ta = 0.0041; LFparameters.tc = 0.5817; case 'fry' LFparameters.tp = 0.4808; LFparameters.te = 0.5955; LFparameters.ta = 0.0269; LFparameters.tc = 0.7200; case 'breathy' LFparameters.tp = 0.4621; LFparameters.te = 0.6604; LFparameters.ta = 0.0270; LFparameters.tc = 0.7712; end lfpModal = [0.4134 0.5530 0.0041 0.5817]; lfpBreathy = [0.4621 0.6604 0.0270 0.7712]; lfpFry = [0.4808 0.5955 0.0269 0.7200]; lfpDisplay = 0.4*lfpModal+0.3*lfpBreathy+0.3*lfpFry; LFparameters.tp = lfpDisplay(1); LFparameters.te = lfpDisplay(2); LFparameters.ta = lfpDisplay(3); LFparameters.tc = lfpDisplay(4); set(updatedHandles.tpText,'string',['tp:' num2str(LFparameters.tp*100,'%7.3f')]); set(updatedHandles.teText,'string',['te:' num2str(LFparameters.te*100,'%7.3f')]); set(updatedHandles.taText,'string',['ta:' num2str(LFparameters.ta*100,'%7.3f')]); set(updatedHandles.tcText,'string',['tc:' num2str(LFparameters.tc*100,'%7.3f')]); modelOut = sourceByLFmodelAAF(LFparameters.timeForDisplay,LFparameters.tp, ... LFparameters.te,LFparameters.ta,LFparameters.tc,0.01); axes(handles.sourceAxis); plot(LFparameters.timeForDisplay([1 end]),[0 0]); hold on; updatedHandles.sourceHandle = plot(LFparameters.timeForDisplay,modelOut.source,'k','linewidth',2); set(gca,'xlim',[0 1],'ylim',[min(modelOut.source) max(modelOut.source)]); ylimSource = get(handles.sourceAxis,'ylim'); updatedHandles.tpHandle = plot(LFparameters.tp*[1 1],[0 ylimSource(2)],'b'); updatedHandles.teHandle = plot(LFparameters.te*[1 1],[ylimSource(1) 0],'b'); taXline = LFparameters.ta/abs(ylimSource(1))*diff(ylimSource); updatedHandles.taHandle = plot(LFparameters.te+[0 taXline],ylimSource,'r'); updatedHandles.taTopHandle = plot(LFparameters.te+taXline,ylimSource(2),'r.','markersize',40); updatedHandles.tcHandle = plot(LFparameters.tc*[1 1],ylimSource,'b'); axis off; axes(handles.vvAxis); plot(LFparameters.timeForDisplay([1 end]),[0 0]); hold on; updatedHandles.vvHandle = plot(LFparameters.timeForDisplay,modelOut.volumeVerocity,'k','linewidth',2); set(gca,'xlim',[0 1],'ylim',[0 max(modelOut.volumeVerocity)]); fftl = 8192*2; fx = (0:fftl-1)'/fftl*fsPlot; axis off axes(handles.spectrumAxis); sourceSpectrum = 20*log10(abs(fft(modelOut.source,fftl))); updatedHandles.sourceSpectrum = sourceSpectrum; updatedHandles.LFmodelGenericFaxis = fx; frequencyWeight = 20*log10(fx); levelAtF0 = interp1(fx,sourceSpectrum+frequencyWeight,1); updatedHandles.spectrumHandle = semilogx(fx,sourceSpectrum+frequencyWeight-levelAtF0,'k','linewidth',2); set(gca,'xlim',[1 40],'ylim',[-20 20],'fontsize',14); hold on; modal = sourceByLFmodelAAF(LFparameters.timeForDisplay,lfpModal(1), ... lfpModal(2),lfpModal(3),lfpModal(4),0.01); sourceSpectrumModal = 20*log10(abs(fft(modal.source,fftl))); levelAtF0 = interp1(fx,sourceSpectrumModal+frequencyWeight,1); semilogx(fx,sourceSpectrumModal+frequencyWeight-levelAtF0,'b'); breathy = sourceByLFmodelAAF(LFparameters.timeForDisplay,lfpBreathy(1), ... lfpBreathy(2),lfpBreathy(3),lfpBreathy(4),0.01); sourceSpectrumBreathy = 20*log10(abs(fft(breathy.source,fftl))); levelAtF0 = interp1(fx,sourceSpectrumBreathy+frequencyWeight,1); semilogx(fx,sourceSpectrumBreathy+frequencyWeight-levelAtF0,'r'); fry = sourceByLFmodelAAF(LFparameters.timeForDisplay,lfpFry(1), ... lfpFry(2),lfpFry(3),lfpFry(4),0.01); sourceSpectrumFry = 20*log10(abs(fft(fry.source,fftl))); levelAtF0 = interp1(fx,sourceSpectrumFry+frequencyWeight,1); semilogx(fx,sourceSpectrumFry+frequencyWeight-levelAtF0,'g'); legend('test','modal','breathy','vocal fry','location','southwest'); xlabel('frequency (re. 1/T0)'); ylabel('level (dB re. at F0)'); title('source spectrum with +6dB/oct emphasis'); grid on; %--- equalizer design %cosineCoefficient = [0.355768 0.487396 0.144232 0.012604]; % Nuttall win12 %upperLimit = 50; %halfSample = 50; hc = [0.2624710164 0.4265335164 0.2250165621 0.0726831633 0.0125124215 0.0007833203]; updatedHandles.equalizerStr = equalizerDesignAAFX(hc, 68, 80, 1.5); %updatedHandles.equalizerStr = equalizerDesignAAFX(cosineCoefficient,upperLimit,halfSample); %--- set other voicing parameters updatedHandles.LFparameters = LFparameters; updatedHandles.duration = 0.5; % in second updatedHandles.samplingFrequency = 44100; updatedHandles.F0 = 110; updatedHandles.vibratoRate = 5.5; % in Hz updatedHandles.vibratoDepth = 100; % in cent updatedHandles.sampleTime = (0:1/updatedHandles.samplingFrequency:updatedHandles.duration)'; %--- design control sliders axes(handles.f0BaseAxis); updatedHandles.f0BaseBarHandle = plot([0 0],[0 48],'b','linewidth',1); set(gca,'ylim',[0 48]); axis('off') hold on; updatedHandles.f0BaseKnobHandle = plot(0,12,'b+','linewidth',1,'markersize',12); updatedHandles.f0KnobHit = 0; %--- design F0 sketchpad axes(handles.f0PaintingAxis); updatedHandles.referenceF0Handle = plot([0 100],log2(updatedHandles.F0/55)*12*[1 1],'g'); set(gca,'xlim',[0 updatedHandles.duration],'ylim',log2(updatedHandles.F0/55)*12+[-6 6], ... 'ytick',-6:54,'ytickLabel',{' ';'E1';'F1';' ';'G1';' '; ... 'A1';' ';'B1';'C2';' ';'D2';' ';'E2';'F2';' ';'G2';' '; ... 'A2';' ';'B2';'C3';' ';'D3';' ';'E3';'F3';' ';'G3';' '; ... 'A3';' ';'B3';'C4';' ';'D4';' ';'E4';'F4';' ';'G4';' '; ... 'A4';' ';'B4';'C5';' ';'D5';' ';'E5';'F5';' ';'G5';' '; ... 'A5'}); updatedHandles.SketchXtick = [0:0.1:0.2 0.25 0.3:0.1:1 1.5:0.5:15]; updatedHandles.SketchXtickLabel = {'0';' ';' ';'0.25';' ';' ';'0.5'; ... ' ';' ';' ';' ';'1';' ';'2';' ';'3';' ';'4';' ';'5';' '; ... '6';' ';'7';' ';'8';' ';'9';' ';'10';' '; ... '1';' ';'2';' ';'3';' ';'4';' ';'5'}; set(gca,'xtick',updatedHandles.SketchXtick,'xticklabel',updatedHandles.SketchXtickLabel); hold on; xlabel('time (s)'); updatedHandles.sketchFs = 1000; updatedHandles.sketchTimeBase = (0:1/updatedHandles.sketchFs:4)'; updatedHandles.sketchF0 = updatedHandles.F0*2.0.^( ... sin(2*pi*updatedHandles.vibratoRate*updatedHandles.sketchTimeBase)*updatedHandles.vibratoDepth/1200); updatedHandles.sketchF0Base = updatedHandles.F0; updatedHandles.f0TraceHandle = plot(updatedHandles.sketchTimeBase, ... log2(updatedHandles.sketchF0/55)*12,'b'); updatedHandles.f0DraftHandle = plot(updatedHandles.sketchTimeBase, ... log2(updatedHandles.sketchF0/55)*12*NaN); updatedHandles.timeInF0Reference = updatedHandles.duration/2; updatedHandles.timeInF0KnobHandle = plot(updatedHandles.duration/2*[1 1],[-6 56],'g','linewidth',1); grid on; updatedHandles.f0TimeKnobHit = 0; modelName = [handles.sourceModel ' model signal']; set(handles.LFmodelText, 'string', modelName); %--- handler assignment set(handles.LFModelDesignerFigure,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.LFModelDesignerFigure,'windowbuttonDownFcn',@MousebuttonDown); set(handles.saveButton,'enable','off'); end %--- handler for mouse movemnet function moveWhileMouseUp(src,evnt) handles = guidata(src); sourceStructure = guidata(handles.LFModelDesignerFigure); if isInsideAxis(handles.sourceAxis) sourceStructure.f0KnobHit = 0; sourceStructure.f0TimeKnobHit = 0; switch whichLFParameter(sourceStructure) case 'tp' set(src,'Pointer','hand'); set(sourceStructure.tpHandle,'linewidth',2); case 'te' set(src,'Pointer','hand'); set(sourceStructure.teHandle,'linewidth',2); case 'ta' set(src,'Pointer','hand'); set(sourceStructure.taHandle,'linewidth',2); case 'tc' set(src,'Pointer','hand'); set(sourceStructure.tcHandle,'linewidth',2); otherwise set(src,'Pointer','cross'); set(sourceStructure.tpHandle,'linewidth',1); set(sourceStructure.teHandle,'linewidth',1); set(sourceStructure.tcHandle,'linewidth',1); set(sourceStructure.taHandle,'linewidth',1); end elseif isInsideAxis(handles.f0BaseAxis) && strcmp(handles.variableF0,'on') currentPoint = get(handles.f0BaseAxis,'currentPoint'); knobPosition = get(handles.f0BaseKnobHandle,'ydata'); f0BarXlim = get(handles.f0BaseAxis,'xlim'); if abs(currentPoint(1,2)-knobPosition) < 0.3 ... && abs(currentPoint(1,1)) < diff(f0BarXlim)*0.1 set(handles.f0BaseKnobHandle,'linewidth',3); set(handles.f0BaseBarHandle,'linewidth',3); sourceStructure.f0KnobHit = 1; set(src,'Pointer','hand'); else set(handles.f0BaseKnobHandle,'linewidth',1); set(handles.f0BaseBarHandle,'linewidth',1); sourceStructure.f0KnobHit = 0; set(src,'Pointer','arrow'); end elseif isInsideAxis(handles.f0PaintingAxis) && strcmp(handles.variableF0,'on') currentPoint = get(handles.f0PaintingAxis,'currentPoint'); timeKnobPosition = get(handles.timeInF0KnobHandle,'xdata'); f0SketchXlim = get(handles.f0PaintingAxis,'xlim'); f0SketchWidth = diff(f0SketchXlim); if abs(currentPoint(1,1)-timeKnobPosition(1))< f0SketchWidth/50 set(src,'Pointer','hand'); sourceStructure.f0TimeKnobHit = 1; set(handles.timeInF0KnobHandle,'linewidth',3); else set(handles.timeInF0KnobHandle,'linewidth',1); sourceStructure.f0TimeKnobHit = 0; set(src,'Pointer','cross'); end else set(src,'Pointer','arrow'); set(sourceStructure.tpHandle,'linewidth',1); set(sourceStructure.teHandle,'linewidth',1); set(sourceStructure.tcHandle,'linewidth',1); set(sourceStructure.taHandle,'linewidth',1); set(handles.f0BaseKnobHandle,'linewidth',1); set(handles.f0BaseBarHandle,'linewidth',1); handles.f0KnobHit = 0; end switch handles.variableF0 case 'off' set(handles.f0PaintingAxis,'visible','off'); set(handles.f0BaseAxis,'visible','off'); set(handles.timeInF0KnobHandle,'visible','off'); set(handles.f0BaseKnobHandle,'visible','off'); set(handles.f0BaseBarHandle,'visible','off'); set(handles.f0TraceHandle,'visible','off'); set(handles.referenceF0Handle,'visible','off'); set(handles.f0DraftHandle,'visible','off'); case 'on' set(handles.f0PaintingAxis,'visible','on'); %set(handles.f0BaseAxis,'visible','on'); set(handles.timeInF0KnobHandle,'visible','on'); set(handles.f0BaseKnobHandle,'visible','on'); set(handles.f0BaseBarHandle,'visible','on'); set(handles.f0TraceHandle,'visible','on'); set(handles.referenceF0Handle,'visible','on'); set(handles.f0DraftHandle,'visible','on'); end guidata(handles.LFModelDesignerFigure,sourceStructure); end function moveTimeWhileMouseDown(src,evnt) handles = guidata(src); sourceStructure = guidata(handles.LFModelDesignerFigure); currentPoint = get(handles.f0PaintingAxis,'currentPoint'); xlim = get(handles.f0PaintingAxis,'xlim'); biasTerm = currentPoint(1,1)/sourceStructure.timeInF0Reference; biasTerm = min(1/0.25*xlim(2),max(1/4*xlim(2),biasTerm)); sourceStructure.biasTime = biasTerm; timeInF0KnobHandlePosition = sourceStructure.biasTime*sourceStructure.timeInF0Reference; set(handles.timeInF0KnobHandle,'xdata',timeInF0KnobHandlePosition*[1 1]); xData = get(handles.f0DraftHandle,'xdata')*sourceStructure.biasTime; set(handles.f0PaintingAxis,'xtick',sourceStructure.SketchXtick*sourceStructure.biasTime); set(handles.f0TraceHandle,'xdata',xData); guidata(handles.LFModelDesignerFigure,sourceStructure); end function moveF0WhileMouseDown(src,evnt) handles = guidata(src); sourceStructure = guidata(handles.LFModelDesignerFigure); currentPoint = get(handles.f0BaseAxis,'currentPoint'); ylim = get(handles.f0BaseAxis,'ylim'); sourceStructure.f0BaseKnobValue = max(ylim(1),min(ylim(2),currentPoint(1,2))); set(handles.f0BaseKnobHandle,'ydata',sourceStructure.f0BaseKnobValue); f0Base = 55*2.0^(sourceStructure.f0BaseKnobValue/12); set(handles.f0BaseText,'string',[num2str(f0Base,'%6.1f'),' Hz']); set(handles.f0PaintingAxis,'ylim',sourceStructure.f0BaseKnobValue+[-6 6]); set(handles.referenceF0Handle,'ydata',sourceStructure.f0BaseKnobValue*[1 1]); sourceStructure.sketchF0 = sourceStructure.sketchF0/sourceStructure.sketchF0Base*f0Base; sourceStructure.sketchF0Base = f0Base; set(sourceStructure.f0TraceHandle,'ydata',log2(sourceStructure.sketchF0/55)*12); sourceStructure = updateDisplay(sourceStructure); guidata(handles.LFModelDesignerFigure,sourceStructure); end function MousebuttonDown(src,evnt) handles = guidata(src); sourceStructure = guidata(handles.LFModelDesignerFigure); set(handles.saveButton,'enable','off'); if sourceStructure.f0TimeKnobHit == 1 currentpoint = get(handles.f0PaintingAxis,'currentPoint'); sourceStructure.f0SketchKnobValue = currentpoint(1,1); set(handles.LFModelDesignerFigure,'WindowButtonMotionFcn',@moveTimeWhileMouseDown); set(handles.LFModelDesignerFigure,'windowbuttonUpFcn',@penUpFunction); guidata(handles.LFModelDesignerFigure,sourceStructure); return; end if sourceStructure.f0KnobHit == 1 currentpoint = get(handles.f0BaseAxis,'currentPoint'); sourceStructure.f0BaseKnobValue = currentpoint(1,2); %set(handles.f0BaseKnobHandle,'color',[0 1 0]); set(handles.f0BaseBarHandle,'color',[0 1 0]); set(handles.LFModelDesignerFigure,'WindowButtonMotionFcn',@moveF0WhileMouseDown); set(handles.LFModelDesignerFigure,'windowbuttonUpFcn',@penUpFunction); guidata(handles.LFModelDesignerFigure,sourceStructure); return; end switch get(src,'Pointer') case 'hand' sourceStructure.currentLFParameter = whichLFParameter(sourceStructure); switch sourceStructure.currentLFParameter case 'tp' set(sourceStructure.tpHandle,'linewidth',5); xdata = get(sourceStructure.tpHandle,'xdata'); sourceStructure.lastPosition = xdata(1); case 'te' set(sourceStructure.teHandle,'linewidth',5); xdata = get(sourceStructure.teHandle,'xdata'); sourceStructure.lastPosition = xdata(1); case 'ta' set(sourceStructure.taHandle,'linewidth',5); xdata = get(sourceStructure.taTopHandle,'xdata'); sourceStructure.lastPosition = xdata(1); case 'tc' set(sourceStructure.tcHandle,'linewidth',5); xdata = get(sourceStructure.tcHandle,'xdata'); sourceStructure.lastPosition = xdata(1); end set(handles.LFModelDesignerFigure,'WindowButtonMotionFcn',@moveVTLWhileMouseDown); set(handles.LFModelDesignerFigure,'windowbuttonUpFcn',@penUpFunction); end guidata(handles.LFModelDesignerFigure,sourceStructure); end function moveVTLWhileMouseDown(src,evnt) handles = guidata(src); sourceStructure = guidata(handles.LFModelDesignerFigure); currentPoint = get(handles.sourceAxis,'currentPoint'); fsDisplay = 1000; normalizedTime = (-0.2:1/fsDisplay:1.2); tp = sourceStructure.LFparameters.tp; te = sourceStructure.LFparameters.te; ta = sourceStructure.LFparameters.ta; tc = sourceStructure.LFparameters.tc; nyqFreq = fsDisplay/2; Tw = 2/nyqFreq; modelOut = sourceByLFmodelAAF(normalizedTime,tp,te,ta,tc,Tw); switch sourceStructure.currentLFParameter case 'tp' sourceStructure.LFparameters.tp = min(sourceStructure.LFparameters.te-0.02,... max(sourceStructure.LFparameters.te/2+0.02,currentPoint(1,1))); set(sourceStructure.tpHandle,'xdata',sourceStructure.LFparameters.tp*[1 1]); case 'te' teToTc = sourceStructure.LFparameters.tc-sourceStructure.LFparameters.te; sourceStructure.LFparameters.te = max(sourceStructure.LFparameters.tp+0.02,... min(sourceStructure.LFparameters.tp*2-0.02,currentPoint(1,1))); sourceStructure.LFparameters.tc = min(1,teToTc+sourceStructure.LFparameters.te); sourceStructure.LFparameters.te = ... min(sourceStructure.LFparameters.tc-ta-0.02,sourceStructure.LFparameters.te); set(sourceStructure.teHandle,'xdata',sourceStructure.LFparameters.te*[1 1]); set(sourceStructure.tcHandle,'xdata',sourceStructure.LFparameters.tc*[1 1]); taTopValue = getTaTopValue(handles); set(sourceStructure.taTopHandle,'xdata',sourceStructure.LFparameters.te+taTopValue); set(sourceStructure.taHandle,'xdata',sourceStructure.LFparameters.te+[0 taTopValue]); case 'ta' ylimit = get(handles.sourceAxis,'ylim'); if sum(isnan(modelOut.source)) == 0 taYinitial = interp1(normalizedTime,modelOut.source,te,'linear','extrap'); topMarginCoeffient = (ylimit(2)-taYinitial)/abs(taYinitial); else topMarginCoeffient = diff(ylimit)/abs(ylimit(1)); end topMargin = topMarginCoeffient* ... (sourceStructure.LFparameters.tc-sourceStructure.LFparameters.te)+sourceStructure.LFparameters.te; taTopX = min(topMargin-0.02*topMarginCoeffient,max(sourceStructure.LFparameters.te+0.0035,currentPoint(1,1))); set(sourceStructure.taTopHandle,'xdata',taTopX); tmpXdata = get(sourceStructure.taHandle,'xdata'); set(sourceStructure.taHandle,'xdata',[tmpXdata(1) taTopX]); taValue = taTopToTaValue(handles); sourceStructure.LFparameters.ta = taValue; case 'tc' sourceStructure.LFparameters.tc = max(sourceStructure.LFparameters.te+ ... sourceStructure.LFparameters.ta+0.02,min(1,currentPoint(1,1))); set(sourceStructure.tcHandle,'xdata',sourceStructure.LFparameters.tc*[1 1]); otherwise set(src,'Pointer','cross'); end sourceStructure = updateDisplay(sourceStructure); guidata(handles.LFModelDesignerFigure,sourceStructure); end function sourceStructure = updateDisplay(sourceStructure) fsDisplay = 1000; normalizedTime = (-0.2:1/fsDisplay:1.2); tp = sourceStructure.LFparameters.tp; te = sourceStructure.LFparameters.te; ta = sourceStructure.LFparameters.ta; tc = sourceStructure.LFparameters.tc; nyqFreq = fsDisplay/2; Tw = 2/nyqFreq; modelOut = sourceByLFmodelAAF(normalizedTime,tp,te,ta,tc,Tw); if sum(isnan(modelOut.source)) == 0 set(sourceStructure.sourceHandle,'xdata',normalizedTime,'ydata',modelOut.source); set(sourceStructure.sourceAxis,'ylim',[min(modelOut.source) max(modelOut.source)]); ylimit = get(sourceStructure.sourceAxis,'ylim'); set(sourceStructure.tpHandle,'ydata',[0 max(modelOut.source)],'xdata',tp*[1 1]); set(sourceStructure.teHandle,'ydata',[min(modelOut.source) 0],'xdata',te*[1 1]); %taXtop = te+diff(ylimit)/abs(ylimit(1))*ta; taYinitial = interp1(normalizedTime,modelOut.source,te,'linear','extrap'); taXtop = te+(ylimit(2)-taYinitial)/abs(taYinitial)*ta; set(sourceStructure.taHandle,'ydata',[taYinitial max(modelOut.source)], ... 'xdata',[te taXtop]); set(sourceStructure.taTopHandle,'ydata',max(modelOut.source),'xdata',taXtop); set(sourceStructure.tcHandle,'ydata',[min(modelOut.source) max(modelOut.source)], ... 'xdata',tc*[1 1]); set(sourceStructure.vvHandle,'xdata',normalizedTime,'ydata',modelOut.volumeVerocity); set(sourceStructure.vvAxis,'ylim',[0 max(modelOut.volumeVerocity)]); fftl = 8192*2; fx = (0:fftl-1)'/fftl*fsDisplay; sourceSpectrum = 20*log10(abs(fft(modelOut.source,fftl))); frequencyWeight = 20*log10(fx); levelAtF0 = interp1(fx,sourceSpectrum+frequencyWeight,1); ydata = sourceSpectrum+frequencyWeight-levelAtF0; set(sourceStructure.spectrumHandle,'ydata',ydata); if max(ydata(fx<50))>20 set(sourceStructure.spectrumAxis,'ylim',[-20 max(ydata(fx<50))]); else set(sourceStructure.spectrumAxis,'ylim',[-20 20]); end sourceStructure.LFmodelGenericSpectrum = sourceSpectrum; sourceStructure.LFmodelGenericFaxis = fx; if isfield(sourceStructure,'parentUserData') parentUserData = guidata(sourceStructure.parentUserData.vtTester); if isfield(parentUserData,'F0') %disp('F0 exist') switch parentUserData.variableF0 case 'on' f0Base = sourceStructure.sketchF0Base; parentUserData.F0 = f0Base; guidata(sourceStructure.parentUserData.vtTester,parentUserData); case 'off' f0Base = parentUserData.F0; end else f0Base = 125; end modelFaxis = get(parentUserData.gainPlotHandle,'xdata')/parentUserData.vtLength*parentUserData.vtLengthReference; modelVTgain = get(parentUserData.gainPlotHandle,'ydata'); set(parentUserData.harmonicsHandle,'xdata', ... parentUserData.harmonicAxis*f0Base*parentUserData.vtLength/parentUserData.vtLengthReference); levelAtF0 = interp1(fx,sourceSpectrum,1); sourceGain = interp1(fx*f0Base,sourceSpectrum-levelAtF0, ... modelFaxis*parentUserData.vtLengthReference/parentUserData.vtLength,'linear','extrap'); scaledVTgain = interp1(modelFaxis/parentUserData.vtLengthReference*parentUserData.vtLength,... modelVTgain,modelFaxis,'linear','extrap'); set(parentUserData.totalEnvelopeHandle,'visible','on',... 'xdata',modelFaxis,'ydata',scaledVTgain(:)+sourceGain(:),'linewidth',3); envelopeSpec = scaledVTgain(:)+sourceGain(:); %envelopeFaxis = get(parentUserData.totalEnvelopeHandle,'xdata'); maxEnvelope = max(envelopeSpec(modelFaxis<5000)); inspecFlag = get(parentUserData.inSpectrumHandle,'visible'); switch inspecFlag case 'on' %disp('LF model moved!') inputSpecData = get(parentUserData.inSpectrumHandle,'ydata'); inputSpecFAxis = get(parentUserData.inSpectrumHandle,'xdata'); maxInputSpec = max(inputSpecData(inputSpecFAxis<5000)); set(parentUserData.inSpectrumHandle,'ydata',inputSpecData-maxInputSpec+maxEnvelope); end end set(sourceStructure.tpText,'string',['tp:' num2str(tp*100,'%7.3f')]); set(sourceStructure.teText,'string',['te:' num2str(te*100,'%7.3f')]); set(sourceStructure.taText,'string',['ta:' num2str(ta*100,'%7.3f')]); set(sourceStructure.tcText,'string',['tc:' num2str(tc*100,'%7.3f')]); %if isfield(sourceStructure,'parentUserData') && sourceStructure.parentUserData.releaseToPlay % vtShapeToSoundTestV20('SoundItButton_Callback',sourceStructure.parentUserData.SoundItButton,[], ... % sourceStructure.parentUserData); %end end end function taTopValue = getTaTopValue(handles) %ylimit = get(handles.sourceAxis,'ylim'); %taTopValue = diff(ylimit)/abs(ylimit(1))*handles.LFparameters.ta; sourceStructure = guidata(handles.LFModelDesignerFigure); fsDisplay = 1000; normalizedTime = (-0.2:1/fsDisplay:1.2); tp = sourceStructure.LFparameters.tp; te = sourceStructure.LFparameters.te; ta = sourceStructure.LFparameters.ta; tc = sourceStructure.LFparameters.tc; nyqFreq = fsDisplay/2; Tw = 2/nyqFreq; modelOut = sourceByLFmodelAAF(normalizedTime,tp,te,ta,tc,Tw); if sum(isnan(modelOut.source)) == 0 ylimit = get(sourceStructure.sourceAxis,'ylim'); taYinitial = interp1(normalizedTime,modelOut.source,te,'linear','extrap'); taTopValue = (ylimit(2)-taYinitial)/abs(taYinitial)*ta; end end function taValue = taTopToTaValue(handles) taTop = get(handles.taTopHandle,'xdata'); taBottom = get(handles.taHandle,'xdata'); taBottom = taBottom(1); taHandleYdata = get(handles.taHandle,'ydata'); taBottomY = taHandleYdata(1); %ylimit = get(handles.sourceAxis,'ylim'); %taValue = abs(ylimit(1))/diff(ylimit)*(taTop-taBottom); taValue = abs(taBottomY)/diff(taHandleYdata)*(taTop-taBottom); end function penUpFunction(src,evnt) handles = guidata(src); sourceStructure = guidata(handles.LFModelDesignerFigure); if sourceStructure.f0TimeKnobHit == 1 xlim = get(handles.f0PaintingAxis,'xlim'); set(handles.timeInF0KnobHandle,'xdata',sourceStructure.timeInF0Reference*[1 1]); xData = get(handles.f0DraftHandle,'xdata'); set(handles.f0PaintingAxis,'xlim',[0 xlim(2)/sourceStructure.biasTime]); set(handles.f0TraceHandle,'xdata',xData); set(handles.f0PaintingAxis,'xtick',sourceStructure.SketchXtick); duration = xlim(2)/sourceStructure.biasTime; fs = sourceStructure.samplingFrequency; tt = (0:1/fs:duration)'; set(handles.LFModelDesignerFigure,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.LFModelDesignerFigure,'windowbuttonUpFcn',''); releaseToSound(sourceStructure,handles); return; end if sourceStructure.f0KnobHit == 1 set(handles.f0BaseKnobHandle,'color',[0 0 1]); set(handles.f0BaseBarHandle,'color',[0 0 1]); set(handles.LFModelDesignerFigure,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.LFModelDesignerFigure,'windowbuttonUpFcn',''); releaseToSound(sourceStructure,handles); return; end switch sourceStructure.currentLFParameter case 'tp' xdata = get(sourceStructure.tpHandle,'xdata'); sourceStructure.LFparameters.tp = xdata(1); case 'te' xdata = get(sourceStructure.teHandle,'xdata'); sourceStructure.LFparameters.te = xdata(1); case 'ta' taValue = taTopToTaValue(handles); sourceStructure.LFparameters.ta = taValue; case 'tc' xdata = get(sourceStructure.tcHandle,'xdata'); sourceStructure.LFparameters.tc = xdata(1); end set(sourceStructure.tpHandle,'linewidth',1); set(sourceStructure.teHandle,'linewidth',1); set(sourceStructure.tcHandle,'linewidth',1); set(sourceStructure.taHandle,'linewidth',1); set(handles.LFModelDesignerFigure,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.LFModelDesignerFigure,'windowbuttonUpFcn',''); sourceStructure.currentLFParameter = 'NA'; guidata(handles.LFModelDesignerFigure,sourceStructure); if 1 == 2 if isfield(handles,'parentUserData') handles.parentUserData = guidata(handles.parentUserData.vtTester); set(handles.parentUserData.totalEnvelopeHandle,'linewidth',1); if handles.parentUserData.releaseToPlay %vtShapeToSoundTestV24('SoundItButton_Callback',handles.parentUserData.SoundItButton,[], ... % handles.parentUserData); instruction = 'SoundItButton_Callback'; fName = handles.parentUserData.mfilename; eval([fName '(instruction,handles.parentUserData.SoundItButton,[],handles.parentUserData);']); end end end releaseToSound(sourceStructure,handles); end function releaseToSound(sourceStructure,handles) if isfield(handles,'parentUserData') handles.parentUserData = guidata(handles.parentUserData.vtTester); set(handles.parentUserData.totalEnvelopeHandle,'linewidth',1); if handles.parentUserData.releaseToPlay %vtShapeToSoundTestV24('SoundItButton_Callback',handles.parentUserData.SoundItButton,[], ... % handles.parentUserData); instruction = 'SoundItButton_Callback'; fName = handles.parentUserData.mfilename; eval([fName '(instruction,handles.parentUserData.SoundItButton,[],handles.parentUserData);']); end end end function currentLFParameter = whichLFParameter(sourceStructure) currentLFParameter = 'NA'; tp = sourceStructure.LFparameters.tp; te = sourceStructure.LFparameters.te; tc = sourceStructure.LFparameters.tc; taTopX = get(sourceStructure.taTopHandle,'xdata'); taTopY = get(sourceStructure.taTopHandle,'ydata'); currentPoint = get(sourceStructure.sourceAxis,'currentPoint'); if abs(currentPoint(1,1)-tp)<0.01 && currentPoint(1,2)>0 currentLFParameter = 'tp'; end if abs(currentPoint(1,1)-te)<0.01 && currentPoint(1,2)<0 currentLFParameter = 'te'; end if abs(currentPoint(1,1)-tc)<0.01 currentLFParameter = 'tc'; end if abs(currentPoint(1,1)-taTopX)<0.02 && abs(currentPoint(1,2)-taTopY)<0.02 currentLFParameter = 'ta'; end end function insideInd = isInsideAxis(axisHandle) insideInd = false; currentPoint = get(axisHandle,'currentPoint'); %currentPoint xLimit = get(axisHandle,'xlim'); yLimit = get(axisHandle,'ylim'); if ((currentPoint(1,1)-xLimit(1))*(currentPoint(1,1)-xLimit(2)) < 0) && ... ((currentPoint(1,2)-yLimit(1))*(currentPoint(1,2)-yLimit(2)) < 0) insideInd = true; end end %vibratoDepth = handles.vibratoDepth; %0.25; %vibratoFrequency = handles.vibratoFrequency; %5.5; function f0BaseStr = generateF0baseStructure(handles) f0BaseStr = struct; f0Base = handles.F0; switch get(handles.f0BaseKnobHandle,'visible') case 'off' if isfield(handles,'parentUserData') % 10/Nov./2015 parentUserData = guidata(handles.parentUserData.vtTester); if isfield(parentUserData,'F0') %disp('F0 exist') f0Base = parentUserData.F0; else f0Base = 125; end if isfield(parentUserData,'vibratoFrequency');handles.vibratoRate=parentUserData.vibratoFrequency;end if isfield(parentUserData,'vibratoDepth');handles.vibratoDepth=parentUserData.vibratoDepth;end end fs = handles.samplingFrequency; tt = handles.sampleTime; fVibrato = handles.vibratoRate; depth = handles.vibratoDepth; f0 = 2.0.^(log2(f0Base)+depth/1200*sin(2*pi*fVibrato*tt)); case 'on' fs = handles.samplingFrequency; f0Visible = get(handles.f0TraceHandle,'ydata'); ttVisible = get(handles.f0TraceHandle,'xdata'); xlim = get(handles.f0PaintingAxis,'xlim'); f0Visible = f0Visible(ttVisible<xlim(2)); ttVisible = ttVisible(ttVisible<xlim(2)); f0Trace = 55*2.0.^(f0Visible/12); tt = (0:1/fs:ttVisible(end)); f0 = interp1(ttVisible,f0Trace,tt,'linear','extrap'); end f0BaseStr.f0Trajectory = f0; f0BaseStr.samplingFrequency = fs; f0BaseStr.temporalPositions = tt; end % --- Executes on button press in quitButton. function quitButton_Callback(hObject, eventdata, handles) % hObject handle to quitButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(handles.LFModelDesignerFigure); end function generateSource_Callback(hObject,eventdata,handles) sourceStructure = guidata(handles.LFModelDesignerFigure); parentGuidata = guidata(hObject); vtl = parentGuidata.vtLength; fs = parentGuidata.samplingFrequency/vtl*parentGuidata.vtLengthReference; %fs = sourceStructure.samplingFrequency; LFparameters = sourceStructure.LFparameters; f0BaseStr = generateF0baseStructure(sourceStructure); outStr = AAFLFmodelFromF0Trajectory(f0BaseStr.f0Trajectory,f0BaseStr.temporalPositions,fs, ... LFparameters.tp,LFparameters.te,LFparameters.ta,LFparameters.tc); parentGuidata.outStr = outStr; parentGuidata.generatedF0 = f0BaseStr.f0Trajectory; parentGuidata.generatedTime = f0BaseStr.temporalPositions; parentGuidata.f0Base = sourceStructure.sketchF0Base; parentGuidata.F0 = sourceStructure.sketchF0Base; guidata(hObject,parentGuidata); end % --- Executes on button press in playButton. function playButton_Callback(hObject, eventdata, handles) % hObject handle to playButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) sourceStructure = guidata(handles.LFModelDesignerFigure); fs = sourceStructure.samplingFrequency; LFparameters = sourceStructure.LFparameters; f0BaseStr = generateF0baseStructure(sourceStructure); outStr = AAFLFmodelFromF0Trajectory6T(f0BaseStr.f0Trajectory,f0BaseStr.temporalPositions,fs, ... LFparameters.tp,LFparameters.te,LFparameters.ta,LFparameters.tc); x = outStr.antiAliasedSignal; sourceStructure.synthStructure.LFparameters = LFparameters; sourceStructure.synthStructure.samplingFrequency = fs; sourceStructure.synthStructure.f0BaseStr = f0BaseStr; sourceStructure.synthStructure.synthesisOut = outStr; if sum(isnan(x)) == 0; set(handles.saveButton,'enable','on'); end equalizerStr = sourceStructure.equalizerStr; %xFIR = fftfilt(equalizerStr.response,x); xMin = fftfilt(equalizerStr.minimumPhaseResponseW,x); xMin = xMin/max(abs(xMin))*0.9; %xAnt = fftfilt(equalizerStr.antiCausalResp,x); sourceStructure.player = audioplayer(xMin,fs); play(sourceStructure.player); guidata(handles.LFModelDesignerFigure,sourceStructure); end % --- 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) sourceStructure = guidata(handles.LFModelDesignerFigure); outFileNameRoot = ['LFmodel' datestr(now,30)]; outStructure = struct; outStructure.synthStructure = sourceStructure.synthStructure; outStructure.originalTimeStump = datestr(now); outStructure.creator = 'lfModelDesigner'; [file,path] = uiputfile('*','Save synth. parameters (.mat) and sound at once.',outFileNameRoot); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 disp('Save is cancelled!'); return; end end save([path [file '.mat']],'outStructure'); x = sourceStructure.synthStructure.synthesisOut.antiAliasedSignal; fs = sourceStructure.synthStructure.samplingFrequency; audiowrite([path [file '.wav']],x/max(abs(x))*0.9,fs); end % --- 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) sourceStructure = guidata(handles.LFModelDesignerFigure); [file,path] = uigetfile({'*.mat';'*.txt'},'Select saved .mat file or compliant .txt file'); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 disp('Load is cancelled!'); return; end end switch file(end-2:end) case 'mat' sourceStructure = loadSavedMatFile(sourceStructure,path,file); case 'txt' sourceStructure = loadCompliantTextFile(sourceStructure,path,file); end set(sourceStructure.saveButton,'enable','off'); sourceStructure = updateDisplay(sourceStructure); guidata(handles.LFModelDesignerFigure,sourceStructure); end function sourceStructure = loadCompliantTextFile(sourceStructure,path,file) fid = fopen([path file]); tline = fgetl(fid); fieldChecker = zeros(4,1); tmpLFparameter = struct; while ischar(tline) %disp(tline); readItem = textscan(tline,'%s %f'); switch char(readItem{1}) case 'tp' if ~isempty(readItem{2}) fieldChecker(1) = 1; tmpLFparameter.tp = readItem{2}/100; end case 'te' if ~isempty(readItem{2}) fieldChecker(2) = 1; tmpLFparameter.te = readItem{2}/100; end case 'ta' if ~isempty(readItem{2}) fieldChecker(3) = 1; tmpLFparameter.ta = readItem{2}/100; end case 'tc' if ~isempty(readItem{2}) fieldChecker(4) = 1; tmpLFparameter.tc = readItem{2}/100; end end tline = fgetl(fid); end fclose(fid); if prod(fieldChecker) == 0 disp('Some parameter(s) is(are) missing!'); return; end fsDisplay = 1000; normalizedTime = (-0.2:1/fsDisplay:1.2); nyqFreq = fsDisplay/2; Tw = 2/nyqFreq; modelOut = sourceByLFmodelAAF(normalizedTime,tmpLFparameter.tp,tmpLFparameter.te,... tmpLFparameter.ta,tmpLFparameter.tc,Tw); if sum(isnan(modelOut.source)) == 0 sourceStructure.LFparameters = tmpLFparameter; end end function sourceStructure = loadSavedMatFile(sourceStructure,path,file) tmp = load([path file]); if ~isfield(tmp,'outStructure') disp('field: outStructure is missing!'); return; end if ~isfield(tmp.outStructure,'synthStructure'); disp('field: outStructure.synthStructure is missing'); return; end if ~isfield(tmp.outStructure.synthStructure,'LFparameters'); disp('field: outStructure.synthStructure.LFparameters is missing'); return; end sourceStructure.LFparameters = tmp.outStructure.synthStructure.LFparameters; end % --- Executes on button press in resetButton. function resetButton_Callback(hObject, eventdata, handles) % hObject handle to resetButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) sourceStructure = guidata(handles.LFModelDesignerFigure); switch handles.sourceModel case 'LF' lfpModal = [0.4134 0.5530 0.0041 0.5817]; lfpBreathy = [0.4621 0.6604 0.0270 0.7712]; lfpFry = [0.4808 0.5955 0.0269 0.7200]; lfpDisplay = 0.4*lfpModal+0.3*lfpBreathy+0.3*lfpFry; sourceStructure.LFparameters.tp = lfpDisplay(1); sourceStructure.LFparameters.te = lfpDisplay(2); sourceStructure.LFparameters.ta = lfpDisplay(3); sourceStructure.LFparameters.tc = lfpDisplay(4); case 'FjLj' end set(sourceStructure.saveButton,'enable','off'); sourceStructure.currentLFParameter = 'NA'; sourceStructure = updateDisplay(sourceStructure); guidata(handles.LFModelDesignerFigure,sourceStructure); end
github
HidekiKawahara/SparkNG-master
waveletVisualizer.m
.m
SparkNG-master/GUI/waveletVisualizer.m
32,693
utf_8
7cc7ab0245964392e37e6c3d1cff7bc3
function varargout = waveletVisualizer(varargin) % WAVELETVISUALIZER MATLAB code for waveletVisualizer.fig % WAVELETVISUALIZER, by itself, creates a new WAVELETVISUALIZER or raises the existing % singleton*. % % H = WAVELETVISUALIZER returns the handle to a new WAVELETVISUALIZER or the handle to % the existing singleton*. % % WAVELETVISUALIZER('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in WAVELETVISUALIZER.M with the given input arguments. % % WAVELETVISUALIZER('Property','Value',...) creates a new WAVELETVISUALIZER or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before waveletVisualizer_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to waveletVisualizer_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 % Designed and implemented by Hideki Kawahara % %Copyright 2018 Hideki Kawahara % %Licensed under the Apache License, Version 2.0 (the "License"); %you may not use this file except in compliance with the License. %You may obtain a copy of the License at % % http://www.apache.org/licenses/LICENSE-2.0 % %Unless required by applicable law or agreed to in writing, software %distributed under the License is distributed on an "AS IS" BASIS, %WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %See the License for the specific language governing permissions and %limitations under the License. % Edit the above text to modify the response to help waveletVisualizer % Last Modified by GUIDE v2.5 20-Aug-2019 23:34:17 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @waveletVisualizer_OpeningFcn, ... 'gui_OutputFcn', @waveletVisualizer_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 end % --- Executes just before waveletVisualizer is made visible. function waveletVisualizer_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 waveletVisualizer (see VARARGIN) % Choose default command line output for waveletVisualizer handles.output = hObject; %--- user procedure starts delete(timerfindall); myGUIdata = guidata(hObject); myGUIdata.handles = handles; myGUIdata = setDefault(myGUIdata); myGUIdata = initializeGraphics(myGUIdata); %myGUIdata.displayAttribute = 'Phase'; timerEventInterval = 0.050; % in second myGUIdata.timerEventInterval = timerEventInterval; myGUIdata.avfoDisplay = 110; %--- audio monitor preparation myGUIdata.recordObj1 = audiorecorder(myGUIdata.samplingFrequency,24,1); set(myGUIdata.recordObj1,'TimerPeriod',0.2); myGUIdata.maxTargetPoint = 400;% This is for audio recorder myGUIdata.maxAudioRecorderCount = myGUIdata.maxTargetPoint; myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; set(myGUIdata.counterTxt, 'String', num2str(myGUIdata.audioRecorderCount)); guidata(hObject, myGUIdata); %myGUIdata %--- wave draw timer preparation timerForWaveDraw = timer('TimerFcn',@waveDrawServer,'ExecutionMode','fixedRate', ... 'Period', timerEventInterval,'userData',hObject); myGUIdata.timerForWaveDraw = timerForWaveDraw; set(myGUIdata.startButton, 'enable', 'off'); set(myGUIdata.stopbutton, 'enable', 'on'); set(myGUIdata.quitbutton, 'enable', 'on'); set(myGUIdata.saveButton, 'enable', 'off'); set(myGUIdata.viewerWidthPopup, 'visible', 'off'); set(myGUIdata.fLowPopup, 'visible', 'off'); set(myGUIdata.fHighPopup, 'visible', 'off'); set(myGUIdata.stretchPopup, 'visible', 'off'); set(myGUIdata.defaultButton, 'visible', 'off'); guidata(hObject, myGUIdata); myGUIdata = startRealtime(myGUIdata); %--- myGUIdata.output = hObject; %--- user procedure ends % Update handles structure %guidata(hObject, handles); This is original guidata(hObject, myGUIdata); % UIWAIT makes waveletVisualizer wait for user response (see UIRESUME) % uiwait(handles.excitationViewerGUI); end % --- Outputs from this function are returned to the command line. function varargout = waveletVisualizer_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; end %--- user defined supporting functions starts function myGUIdata = setDefault(myGUIdata) myGUIdata.samplingFrequency = 22050; myGUIdata.channels_in_octave = 8; myGUIdata.low_frequency = 110 * 2^(-1/3);%100; myGUIdata.high_freuency = 5000; myGUIdata.halfTimeSpan = 0.008; % 8 ms (default) myGUIdata.fftl = 2048; myGUIdata.stretching_factor = 1.0; myGUIdata.synchPhase = -120; set(myGUIdata.viewerWidthPopup, 'value', 3); set(myGUIdata.fLowPopup, 'value', 3); set(myGUIdata.fHighPopup, 'value', 2); set(myGUIdata.stretchPopup, 'value', 2); set(myGUIdata.phaseEdit, 'string', -120); end function waveDrawServer(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); xdata = get(myGUIdata.waveHandle,'xdata'); wvltStr = myGUIdata.wvltStr; fc_list = wvltStr.fc_list; max_bias = wvltStr.wvlt(1).bias; n_data = length(xdata); channels_oct = myGUIdata.channels_in_octave; base_index = 1:n_data; buffer_index = 1:3 * n_data; %buffer_index(end) %size(myGUIdata.imageBuffer) switch get(myGUIdata.recordObj1,'running') case 'on' if get(myGUIdata.recordObj1,'TotalSamples') > max_bias * 4 + 3 * n_data myGUIdata.tmpAudio = getaudiodata(myGUIdata.recordObj1); if length(myGUIdata.tmpAudio) > max_bias * 4 + 3 * n_data x = myGUIdata.tmpAudio(end-(max_bias * 4 + 3 * n_data)+1:end); for ii = 1:myGUIdata.n_channles y = fftfilt(wvltStr.wvlt(ii).w, x); myGUIdata.imageBuffer(ii, :) = y(wvltStr.wvlt(ii).bias + wvltStr.wvlt(1).bias + buffer_index); end x_original = x(buffer_index + wvltStr.wvlt(1).bias); instFreqBuffer = angle(myGUIdata.imageBuffer ./ myGUIdata.imageBuffer(:, max(1, buffer_index - 1))); myGUIdata.imageBufferTmp = angle(myGUIdata.imageBuffer); rawSTD = (std(instFreqBuffer(:, 2:end)') * myGUIdata.samplingFrequency / 2 / pi) .^ 2; rawSTD = sqrt(rawSTD([1 1:end-1]) + rawSTD + rawSTD([2:end end])); fsdData = log(rawSTD(:) ./ fc_list(:)); bw_list = 1 ./ ((2^(1/channels_oct/2)-2^(-1/channels_oct/2)) * fc_list * 2 * pi); gd_gram_raw = -diag(bw_list) * angle(myGUIdata.imageBuffer ./ ... myGUIdata.imageBuffer([1 1:end-1], :)); gd_gram = diag(fc_list) * gd_gram_raw; gdData = std(max(-1, min(1, gd_gram(:, 2:end)'))); gdData(1) = gdData(2); gdData = log((gdData([1 1:end-1]) + gdData +gdData([2:end end])) / 3); mixData = gdData(:) + fsdData(:); % mixed cost function for fo [~, min_ch] = min(mixData);%gdData(:) + fsdData(:)); fund_phase = angle(myGUIdata.imageBuffer(min_ch, :) * exp(-1i * myGUIdata.synchPhase / 360 * 2 * pi)); %myGUIdata.synchPhase avfo = mean(instFreqBuffer(min_ch, 2:end)) * myGUIdata.samplingFrequency / 2 / pi; syncID = buffer_index(fund_phase .* fund_phase(max(1, buffer_index - 1)) < 0 & ... fund_phase(max(1, buffer_index - 1)) < fund_phase & ... buffer_index > n_data & buffer_index < buffer_index(end) - n_data); if ~isempty(syncID) [~, bias_center] = min(abs(syncID - buffer_index(end) / 2)); if isempty(bias_center) bias_center = round(buffer_index(end) / 2); end center_id = syncID(bias_center); else center_id = round(buffer_index(end) / 2); end selector = max(1, min(buffer_index(end), base_index + center_id - round(base_index(end) / 2))); fs = myGUIdata.samplingFrequency; contents = cellstr(get(myGUIdata.displayImagePopup,'String')); %myGUIdata.displayAttribute = contents{get(myGUIdata.displayImagePopup,'Value')}; switch contents{get(myGUIdata.displayImagePopup,'Value')} %myGUIdata.displayAttribute case 'Phase' myGUIdata.waveletImage = myGUIdata.imageBufferTmp(:, selector); case 'Inst. Freq. /fc' myGUIdata.waveletImage = max(0.75, min(1.4, diag(1 ./ fc_list)... * instFreqBuffer(:, selector) * fs / 2 / pi)); case 'Group delay*fc' myGUIdata.waveletImage = max(-1, min(1, gd_gram(:, selector))); case 'Absolute value' levelBuf = 20 * log10(abs(myGUIdata.imageBuffer(:, selector))); mx_level = max(max(levelBuf)); myGUIdata.waveletImage = max(mx_level - 70, levelBuf); end myGUIdata.gainData = mean(abs(myGUIdata.imageBuffer(:, selector)) .^ 2, 2); myGUIdata.gainData = 10 * log10(myGUIdata.gainData); set(myGUIdata.wvltImageHandle,'cdata',myGUIdata.waveletImage); set(myGUIdata.freqSDHandle, 'xdata', mixData / max(abs(mixData)) * xdata(end) * 1000); ydata = x_original(base_index + center_id - round(base_index(end) / 2)); set(myGUIdata.waveHandle,'ydata', ydata); set(myGUIdata.dBpowerAxis, 'xlim', [-69 0]); set(myGUIdata.gainHandle, 'xdata', -80 - myGUIdata.gainData); fo_in_channel = 1 + log2(avfo / myGUIdata.low_frequency) * myGUIdata.channels_in_octave; set(myGUIdata.foCursor, 'ydata', fo_in_channel * [1 1]); set(myGUIdata.waveAxis,'ylim',max(abs(ydata))*[-1 1]); set(myGUIdata.foViewer, 'String', num2str(avfo, '%6.1f')); [~, croma_id] = min(abs(avfo - myGUIdata.croma_scale)); myGUIdata.avfoDisplay = myGUIdata.avfoDisplay * 0.0 + avfo * 1.0; [~, croma_id_smooth] = min(abs(myGUIdata.avfoDisplay - myGUIdata.croma_scale)); set(myGUIdata.tunerHandle, 'ydata', [0 0] + ... 1200 * log2(myGUIdata.avfoDisplay / myGUIdata.croma_scale(croma_id_smooth))); set(myGUIdata.noteNameText, 'String', myGUIdata.note_name_struct.name{croma_id_smooth}); end myGUIdata.audioRecorderCount = myGUIdata.audioRecorderCount - 1; set(myGUIdata.counterTxt, 'String', num2str(myGUIdata.audioRecorderCount)); end end switch get(myGUIdata.timerForWaveDraw, 'running') case 'off' start(myGUIdata.timerForWaveDraw); end if myGUIdata.audioRecorderCount < 0 set(myGUIdata.counterTxt, 'String', 'Initializing ...'); switch get(myGUIdata.timerForWaveDraw, 'running') case 'on' stop(myGUIdata.timerForWaveDraw); end switch get(myGUIdata.recordObj1,'running') case 'on' stop(myGUIdata.recordObj1); end myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata = startRealtime(myGUIdata); end guidata(handleForTimer,myGUIdata); end function myGUIdata = startRealtime(myGUIdata) myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.lastPosition = 1; record(myGUIdata.recordObj1); pause(0.3) switch get(myGUIdata.timerForWaveDraw,'running') case 'off' start(myGUIdata.timerForWaveDraw); case 'on' otherwise disp('timer is bloken!'); end end function myGUIdata = initializeGraphics(myGUIdata) waveAxisHandle = myGUIdata.waveAxis; fs = myGUIdata.samplingFrequency; %------ waveform display halfTimeSpan = myGUIdata.halfTimeSpan; axes(waveAxisHandle); time_axis = (-round(halfTimeSpan * fs):round(halfTimeSpan * fs)) / fs; myGUIdata.waveHandle = plot(time_axis, randn(length(time_axis), 1), 'k'); set(gca, 'xlim', halfTimeSpan*[-1 1], 'fontsize', 14, 'xtick', [], 'ytick', []); %xlabel('time (s)') grid on; %------- wavelet display axes(myGUIdata.waveletAxis); wvltStr = designCos6Wavelet(fs, myGUIdata.low_frequency, myGUIdata.high_freuency, ... myGUIdata.fftl, myGUIdata.stretching_factor, myGUIdata.channels_in_octave); myGUIdata.n_channles = length(wvltStr.fc_list); waveletImage = zeros(myGUIdata.n_channles, length(time_axis)); for ii = 1:myGUIdata.n_channles waveletImage(ii, :) = cos(time_axis / halfTimeSpan * pi * wvltStr.fc_list(ii) / wvltStr.fc_list(1)); end myGUIdata.wvltImageHandle = imagesc(halfTimeSpan*[-1 1] * 1000, ... [1 myGUIdata.n_channles], waveletImage); axis('xy'); colormap(hsv); hold all myGUIdata.freqSDHandle = plot(zeros(myGUIdata.n_channles, 1), ... (1:myGUIdata.n_channles), 'w', 'linewidth', 3); fc_list = wvltStr.fc_list; ytickFreq = [50 60 70 80 90 100 200 300 400 500 600 700 800 900 1000 2000 3000 4000 5000]; ytick = interp1(log(fc_list), 1:length(fc_list), log(ytickFreq), 'linear', 'extrap'); ytickLabel = num2str(ytickFreq', '%4.0f'); set(gca, 'fontsize', 14, 'ytick', ytick, 'ytickLabel', ytickLabel, ... 'ylim', [1 myGUIdata.n_channles],'xlim', halfTimeSpan*[-1 1] * 1000); xlabel('time (ms)') ylabel('frequency (Hz)'); %-------- wavelet level display axes(myGUIdata.dBpowerAxis); gainv = zeros(length(fc_list), 1) - 15; for ii = 1:length(ytick) plot([-60 0], [1 1] * ytick(ii), 'color', [0.5 0.5 0.5]); hold all end croma_base = 27.5; croma_scale = croma_base * 2 .^ (0:1 / 12:log2(myGUIdata.high_freuency / croma_base)); croma_scale_channel = 1 + log2(croma_scale / myGUIdata.low_frequency) * myGUIdata.channels_in_octave; for ii = 1:length(croma_scale) plot([-69 -60], [1 1] * croma_scale_channel(ii), 'g'); end for ii = 2:7 if ii * 12 + 1 <= length(croma_scale_channel) && ... ii * 12 + 1 + 3 - 12 <= length(croma_scale_channel) && ... ii * 12 + 1 + 3 + 4 - 12 <= length(croma_scale_channel) text(-66, croma_scale_channel(ii * 12 + 1), ['A' num2str(ii)]) text(-66, croma_scale_channel(ii * 12 + 1 + 3 - 12), ['C' num2str(ii)]) text(-66, croma_scale_channel(ii * 12 + 1 + 3 + 4 - 12), ['E' num2str(ii)]) end end note_name_base = {'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'}; note_name_struct = struct; for ii = 4:length(croma_scale) note_index = rem((ii - 4), 12) + 1; octave_id = floor(log2(croma_scale(ii) / croma_scale(4))) + 1; note_name_struct.name{ii} = [note_name_base{note_index} num2str(octave_id)]; end myGUIdata.note_name_struct = note_name_struct; myGUIdata.foCursor = plot([-60 0], [5 5], 'c', 'linewidth', 3); myGUIdata.gainHandle = plot(gainv, 1:length(fc_list), 'k', 'linewidth', 2); axis([-69 0 1 length(fc_list)]); grid on; xlabel('level (rel. dB)'); %xtick = get(gca, 'xtick'); xtick = -60:10:0; xtickLabel = num2str(xtick(end:-1:1)'); set(gca, 'ytick', [], 'fontsize', 14, 'xtick', xtick, 'xtickLabel', xtickLabel, 'xlim', [-69 0]); myGUIdata.gainData = get(myGUIdata.gainHandle, 'xdata'); %---- tuner display axes(myGUIdata.tunerAxis) plot([-1 1], [0 0], 'k', 'linewidth', 2) hold all myGUIdata.tunerHandle = plot([-1 1], [0 0] + 0.2, 'g', 'linewidth', 5); axis([-1 1 -50 50]); set(gca, 'ytick', [], 'xtick', [], 'linewidth', 2); myGUIdata.croma_scale = croma_scale; myGUIdata.wvltStr = wvltStr; myGUIdata.waveletImage = waveletImage; myGUIdata.imageBuffer = zeros(myGUIdata.n_channles, length(time_axis) * 3); myGUIdata.imageBufferTmp = zeros(myGUIdata.n_channles, length(time_axis) * 3); myGUIdata.instFreqBuffer = zeros(myGUIdata.n_channles, length(time_axis) * 3); %myGUIdata.displayAttribute = 'Phase'; update_colormap(myGUIdata); end function update_colormap(myGUIdata) contents = cellstr(get(myGUIdata.displayImagePopup,'String')); %myGUIdata.displayAttribute = contents{get(hObject,'Value')}; switch contents{get(myGUIdata.displayImagePopup,'Value')} %myGUIdata.displayAttribute case 'Phase' colormap(hsv); case 'Inst. Freq. /fc' colormap(hsv); case 'Group delay*fc' colormap(hsv); case 'Absolute value' colormap(jet); end end %--- user defined supporting functions ends % --- Executes on button press in startButton. function startButton_Callback(hObject, eventdata, handles) % hObject handle to startButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(hObject); myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; record(myGUIdata.recordObj1); pause(0.3) start(myGUIdata.timerForWaveDraw); set(myGUIdata.startButton, 'enable', 'off'); set(myGUIdata.stopbutton, 'enable', 'on'); set(myGUIdata.quitbutton, 'enable', 'on'); set(myGUIdata.saveButton, 'enable', 'off'); guidata(hObject, myGUIdata); end % --- Executes on button press in stopbutton. function stopbutton_Callback(hObject, eventdata, handles) % hObject handle to stopbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(hObject); switch get(myGUIdata.timerForWaveDraw, 'running') case 'on' stop(myGUIdata.timerForWaveDraw); end switch get(myGUIdata.recordObj1, 'running') case 'on' stop(myGUIdata.recordObj1); end set(myGUIdata.startButton, 'enable', 'on'); set(myGUIdata.stopbutton, 'enable', 'off'); set(myGUIdata.quitbutton, 'enable', 'on'); set(myGUIdata.saveButton, 'enable', 'on'); guidata(hObject, myGUIdata); end % --- Executes on button press in quitbutton. function quitbutton_Callback(hObject, eventdata, handles) % hObject handle to quitbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(hObject); stop(myGUIdata.timerForWaveDraw); delete(timerfindall); stop(myGUIdata.recordObj1); close(handles.excitationViewerGUI); end % --- Executes on selection change in displayImagePopup. function displayImagePopup_Callback(hObject, eventdata, handles) % hObject handle to displayImagePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns displayImagePopup contents as cell array % contents{get(hObject,'Value')} returns selected item from displayImagePopup stopbutton_Callback(hObject, eventdata, handles); myGUIdata = guidata(hObject); contents = cellstr(get(hObject,'String')); %myGUIdata.displayAttribute = contents{get(hObject,'Value')}; axes(myGUIdata.waveletAxis); update_colormap(myGUIdata); %switch contents{get(hObject,'Value')} %myGUIdata.displayAttribute % case 'Phase' % colormap(hsv); % case 'Inst. Freq. /fc' % colormap(hsv); % case 'Group delay*fc' % colormap(hsv); % case 'Absolute value' % colormap(jet); %end guidata(hObject, myGUIdata); startButton_Callback(hObject, eventdata, handles); end % --- Executes during object creation, after setting all properties. function displayImagePopup_CreateFcn(hObject, eventdata, handles) % hObject handle to displayImagePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- 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) myGUIdata = guidata(hObject); outFileName = ['snapD' datestr(now, 30) '.wav']; audiowrite( outFileName, myGUIdata.tmpAudio, myGUIdata.samplingFrequency, ... 'BitsPerSample', 32); disp(['snapshot file:' outFileName]); set(myGUIdata.saveButton, 'enable', 'off'); end % --- Executes on selection change in modePopup. function modePopup_Callback(hObject, eventdata, handles) % hObject handle to modePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns modePopup contents as cell array % contents{get(hObject,'Value')} returns selected item from modePopup myGUIdata = guidata(hObject); contents = cellstr(get(hObject,'String')); myGUIdata.operationMode = contents{get(hObject,'Value')}; switch myGUIdata.operationMode case 'Normal' set(myGUIdata.viewerWidthPopup, 'visible', 'off'); set(myGUIdata.fLowPopup, 'visible', 'off'); set(myGUIdata.fHighPopup, 'visible', 'off'); set(myGUIdata.defaultButton, 'visible', 'off'); set(myGUIdata.stretchPopup, 'visible', 'off'); case 'Experimental' set(myGUIdata.viewerWidthPopup, 'visible', 'on'); set(myGUIdata.fLowPopup, 'visible', 'on'); set(myGUIdata.fHighPopup, 'visible', 'on'); set(myGUIdata.defaultButton, 'visible', 'on'); set(myGUIdata.stretchPopup, 'visible', 'on'); end guidata(hObject, myGUIdata); end % --- Executes during object creation, after setting all properties. function modePopup_CreateFcn(hObject, eventdata, handles) % hObject handle to modePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on selection change in fHighPopup. function fHighPopup_Callback(hObject, eventdata, handles) % hObject handle to fHighPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns fHighPopup contents as cell array % contents{get(hObject,'Value')} returns selected item from fHighPopup stopbutton_Callback(hObject, eventdata, handles); myGUIdata = guidata(hObject); contents = cellstr(get(hObject,'String')); viewWidthstring = contents{get(hObject,'Value')}; stringValue = sscanf(viewWidthstring, '%s %f %s'); myGUIdata.high_freuency = stringValue(4); delete(myGUIdata.wvltImageHandle); delete(myGUIdata.gainHandle); cla(myGUIdata.tunerAxis); cla(myGUIdata.dBpowerAxis); cla(myGUIdata.waveletAxis); cla(myGUIdata.waveAxis); myGUIdata = initializeGraphics(myGUIdata); guidata(hObject, myGUIdata); startButton_Callback(hObject, eventdata, handles); end % --- Executes during object creation, after setting all properties. function fHighPopup_CreateFcn(hObject, eventdata, handles) % hObject handle to fHighPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on selection change in fLowPopup. function fLowPopup_Callback(hObject, eventdata, handles) % hObject handle to fLowPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns fLowPopup contents as cell array % contents{get(hObject,'Value')} returns selected item from fLowPopup stopbutton_Callback(hObject, eventdata, handles); myGUIdata = guidata(hObject); contents = cellstr(get(hObject,'String')); viewWidthstring = contents{get(hObject,'Value')}; stringValue = sscanf(viewWidthstring, '%s %f %s'); myGUIdata.low_frequency = stringValue(4); delete(myGUIdata.wvltImageHandle); delete(myGUIdata.gainHandle); cla(myGUIdata.tunerAxis); cla(myGUIdata.dBpowerAxis); cla(myGUIdata.waveletAxis); cla(myGUIdata.waveAxis); myGUIdata = initializeGraphics(myGUIdata); guidata(hObject, myGUIdata); startButton_Callback(hObject, eventdata, handles); end % --- Executes during object creation, after setting all properties. function fLowPopup_CreateFcn(hObject, eventdata, handles) % hObject handle to fLowPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on selection change in viewerWidthPopup. function viewerWidthPopup_Callback(hObject, eventdata, handles) % hObject handle to viewerWidthPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns viewerWidthPopup contents as cell array % contents{get(hObject,'Value')} returns selected item from viewerWidthPopup stopbutton_Callback(hObject, eventdata, handles); myGUIdata = guidata(hObject); contents = cellstr(get(hObject,'String')); viewWidthstring = contents{get(hObject,'Value')}; stringValue = sscanf(viewWidthstring, '%s %f %s'); myGUIdata.halfTimeSpan = stringValue(4) / 2 / 1000; delete(myGUIdata.wvltImageHandle); delete(myGUIdata.gainHandle); cla(myGUIdata.tunerAxis); cla(myGUIdata.dBpowerAxis); cla(myGUIdata.waveletAxis); cla(myGUIdata.waveAxis); myGUIdata = initializeGraphics(myGUIdata); guidata(hObject, myGUIdata); startButton_Callback(hObject, eventdata, handles); end % --- Executes during object creation, after setting all properties. function viewerWidthPopup_CreateFcn(hObject, eventdata, handles) % hObject handle to viewerWidthPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on button press in defaultButton. function defaultButton_Callback(hObject, eventdata, handles) % hObject handle to defaultButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) stopbutton_Callback(hObject, eventdata, handles); myGUIdata = guidata(hObject); myGUIdata = setDefault(myGUIdata); cla(myGUIdata.tunerAxis); cla(myGUIdata.dBpowerAxis); cla(myGUIdata.waveletAxis); cla(myGUIdata.waveAxis); myGUIdata = initializeGraphics(myGUIdata); guidata(hObject, myGUIdata); startButton_Callback(hObject, eventdata, handles); end % --- Executes on selection change in stretchPopup. function stretchPopup_Callback(hObject, eventdata, handles) % hObject handle to stretchPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns stretchPopup contents as cell array % contents{get(hObject,'Value')} returns selected item from stretchPopup stopbutton_Callback(hObject, eventdata, handles); myGUIdata = guidata(hObject); contents = cellstr(get(hObject,'String')); viewWidthstring = contents{get(hObject,'Value')}; stringValue = sscanf(viewWidthstring, '%s %f'); myGUIdata.stretching_factor = stringValue(5); delete(myGUIdata.wvltImageHandle); delete(myGUIdata.gainHandle); cla(myGUIdata.tunerAxis); cla(myGUIdata.dBpowerAxis); cla(myGUIdata.waveletAxis); cla(myGUIdata.waveAxis); myGUIdata = initializeGraphics(myGUIdata); guidata(hObject, myGUIdata); startButton_Callback(hObject, eventdata, handles); end % --- Executes during object creation, after setting all properties. function stretchPopup_CreateFcn(hObject, eventdata, handles) % hObject handle to stretchPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end function phaseEdit_Callback(hObject, eventdata, handles) % hObject handle to phaseEdit (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 phaseEdit as text % str2double(get(hObject,'String')) returns contents of phaseEdit as a double if ~isnan(str2double(get(hObject,'String'))) myGUIdata = guidata(hObject); myGUIdata.synchPhase = str2double(get(hObject,'String')); guidata(hObject, myGUIdata); end end % --- Executes during object creation, after setting all properties. function phaseEdit_CreateFcn(hObject, eventdata, handles) % hObject handle to phaseEdit (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 end % --- Executes on selection change in wintypePopUp. function wintypePopUp_Callback(hObject, eventdata, handles) % hObject handle to wintypePopUp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns wintypePopUp contents as cell array % contents{get(hObject,'Value')} returns selected item from wintypePopUp stopbutton_Callback(hObject, eventdata, handles); myGUIdata = guidata(hObject); myGUIdata.wtypeId = get(hObject,'Value'); delete(myGUIdata.wvltImageHandle); delete(myGUIdata.gainHandle); cla(myGUIdata.tunerAxis); cla(myGUIdata.dBpowerAxis); cla(myGUIdata.waveletAxis); cla(myGUIdata.waveAxis); myGUIdata = initializeGraphics(myGUIdata); guidata(hObject, myGUIdata); startButton_Callback(hObject, eventdata, handles); end % --- Executes during object creation, after setting all properties. function wintypePopUp_CreateFcn(hObject, eventdata, handles) % hObject handle to wintypePopUp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end
github
HidekiKawahara/SparkNG-master
realtimeSpectrogramV3.m
.m
SparkNG-master/GUI/realtimeSpectrogramV3.m
23,645
utf_8
dd384dea13ba9edbf74507b6050125a3
function varargout = realtimeSpectrogramV3(varargin) % Running spectrogram in realtime. Type: % realtimeSpectrogramV3 % to start. % Designed and coded by Hideki Kawahara (kawahara AT sys.wakayama-u.ac.jp) % 19/Dec./2013 % 20/Dec./2013 added dynamic range control and zooming and pan tools % 21/Dec./2013 bug fix. Please excuse me! % 22/Dec./2013 added wide-band spectrogram, 1/3 band, ERB_N number, Bark % filter bank simulators % 24/Dec./2013 bug fix of frequency axis labels % 31/Aug./2015 machine independent and resizable % This work is licensed under the Creative Commons % Attribution 4.0 International License. % To view a copy of this license, visit % http://creativecommons.org/licenses/by/4.0/. % REALTIMESPECTROGRAMV3 MATLAB code for realtimeSpectrogramV3.fig % REALTIMESPECTROGRAMV3, by itself, creates a new REALTIMESPECTROGRAMV3 or raises the existing % singleton*. % % H = REALTIMESPECTROGRAMV3 returns the handle to a new REALTIMESPECTROGRAMV3 or the handle to % the existing singleton*. % % REALTIMESPECTROGRAMV3('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in REALTIMESPECTROGRAMV3.M with the given input arguments. % % REALTIMESPECTROGRAMV3('Property','Value',...) creates a new REALTIMESPECTROGRAMV3 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before realtimeSpectrogramV3_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to realtimeSpectrogramV3_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 realtimeSpectrogramV3 % Last Modified by GUIDE v2.5 21-Dec-2013 23:28:52 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @realtimeSpectrogramV3_OpeningFcn, ... 'gui_OutputFcn', @realtimeSpectrogramV3_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 end % --- Executes just before realtimeSpectrogramV3 is made visible. function realtimeSpectrogramV3_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 realtimeSpectrogramV3 (see VARARGIN) % Choose default command line output for realtimeSpectrogramV3 handles.output = hObject; % Update handles structure guidata(hObject, handles); %handles delete(timerfindall); initializeDisplay(handles); myGUIdata = guidata(handles.realTimeSgramGUI); %myGUIdata timerEventInterval = 0.1; % in second %timerEventInterval = 0.075; % in second timer50ms = timer('TimerFcn',@synchDrawGUI, 'Period',timerEventInterval,'ExecutionMode','fixedRate', ... 'userData',handles.realTimeSgramGUI); %handleForTimer = handles.multiScopeMainGUI; % global myGUIdata.timer50ms = timer50ms; myGUIdata.smallviewerWidth = 30; % 30 ms is defaule myGUIdata.recordObj1 = audiorecorder(myGUIdata.samplingFrequency,24,1); set(myGUIdata.recordObj1,'TimerPeriod',0.1); record(myGUIdata.recordObj1) myGUIdata.maxAudioRecorderCount = 200; myGUIdata.maxLevel = -100; myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.displayTypeList = cellstr(get(myGUIdata.displayPopupMenu,'String')); %myGUIdata.displayTypeList = myGUIdata.displayTypeList(1:2); set(myGUIdata.displayPopupMenu,'String',myGUIdata.displayTypeList) myGUIdata.displayType = myGUIdata.displayTypeList{1}; guidata(handles.realTimeSgramGUI,myGUIdata); startButton_Callback(hObject, eventdata, handles) % UIWAIT makes realtimeSpectrogramV3 wait for user response (see UIRESUME) % uiwait(handles.realTimeSgramGUI); end function initializeDisplay(handles) myGUIdata = guidata(handles.realTimeSgramGUI); myGUIdata.samplingFrequency = 44100; axes(handles.sgramAxis); myGUIdata = settingForWideband(myGUIdata); fxx = myGUIdata.visibleFrequencyAxis; tx = myGUIdata.timeAxis; myGUIdata.sgramHandle = image([tx(1) tx(end)]-tx(end),[fxx(1) fxx(end)],myGUIdata.initialSgramData); axis('xy'); set(gca,'fontunit','normalized','fontsize',0.025); myGUIdata.linearTicLocationListWide = get(handles.sgramAxis,'ytick'); myGUIdata.linearTickLabelListWide = get(handles.sgramAxis,'ytickLabel'); myGUIdata = settingForNarrowband(myGUIdata); fxx = myGUIdata.visibleFrequencyAxis; tx = myGUIdata.timeAxis; myGUIdata.sgramHandle = image([tx(1) tx(end)]-tx(end),[fxx(1) fxx(end)],myGUIdata.initialSgramData); set(gca,'fontunit','normalized','fontsize',0.03); axis('xy'); %colormap(1-gray) myGUIdata.titleText = title('Narrowband spectrogram','fontunit','normalized','fontsize',0.03); xlabel('time (s)'); ylabel('frequency (Hz)') myGUIdata.linearTicLocationList = get(handles.sgramAxis,'ytick'); myGUIdata.linearTickLabelList = get(handles.sgramAxis,'ytickLabel'); set(myGUIdata.dynamicRanbeText,'string',[num2str(myGUIdata.dynamicRange,'%3.0f') ' dB']); %set(myGUIdata.sgramHandle,'erasemode','none'); set(myGUIdata.displayPopupMenu,'enable','off'); drawnow; guidata(handles.realTimeSgramGUI,myGUIdata); end %--- private function for make it narrow spectrogram function myGUIdata = settingForNarrowband(myGUIdata) myGUIdata.windowLengthInMs = 80; %80 myGUIdata.higherFrequencyLimit = 3600; fs = myGUIdata.samplingFrequency; fftl = 2^ceil(log2(myGUIdata.windowLengthInMs*fs/1000)); %fftl = 1024; fx = (0:fftl/2)/fftl*fs; fxx = fx(fx<myGUIdata.higherFrequencyLimit); frameShift = 0.007; tx = 0:frameShift:4; myGUIdata.initialSgramData = rand(length(fxx),length(tx))*62+1; myGUIdata.frameShift = frameShift; myGUIdata.visibleFrequencyAxis = fxx; myGUIdata.timeAxis = tx; myGUIdata.fftl = fftl; myGUIdata.fftBuffer = zeros(fftl,length(tx)); myGUIdata.lastPosition = 1; myGUIdata.frameShiftInSample = round(myGUIdata.frameShift*fs); %myGUIdata.windowFunction = blackman(round(myGUIdata.windowLengthInMs*fs/1000)); myGUIdata.windowFunction = nuttallwin(round(myGUIdata.windowLengthInMs*fs/1000)); myGUIdata.windowLengthInSample = length(myGUIdata.windowFunction); myGUIdata.dynamicRange = 80; set(myGUIdata.dynamicRangeSlider,'Value',0.2); set(myGUIdata.dynamicRanbeText,'string',[num2str(myGUIdata.dynamicRange,'%3.0f') ' dB']); myGUIdata.maxLevel = -100; end %--- private function for make it narrow spectrogram function myGUIdata = settingForThirdband(myGUIdata) myGUIdata.windowLengthInMs = 80; myGUIdata.higherFrequencyLimit = 3600; fs = myGUIdata.samplingFrequency; fftl = 2^ceil(log2(myGUIdata.windowLengthInMs*fs/1000)); %fftl = 1024; fx = (0:fftl/2)/fftl*fs; %fxx = fx(fx<myGUIdata.higherFrequencyLimit); frameShift = 0.007; tx = 0:frameShift:4; myGUIdata.initialSgramData = rand(length(fx),length(tx))*62+1; switch get(myGUIdata.displayPopupMenu,'Value') case 5 filterBankStr = simulatedFilterBank(myGUIdata.initialSgramData,fx,'third'); case 3 filterBankStr = simulatedFilterBank(myGUIdata.initialSgramData,fx,'ERB'); case 4 filterBankStr = simulatedFilterBank(myGUIdata.initialSgramData,fx,'Bark'); end; myGUIdata.initialSgramData = filterBankStr.filteredSgramTriangle; myGUIdata.frameShift = frameShift; myGUIdata.visibleFrequencyAxis = filterBankStr.fcList; myGUIdata.timeAxis = tx; myGUIdata.fftl = fftl; myGUIdata.fftBuffer = zeros(fftl,length(tx)); myGUIdata.lastPosition = 1; myGUIdata.frameShiftInSample = round(myGUIdata.frameShift*fs); %myGUIdata.windowFunction = blackman(round(myGUIdata.windowLengthInMs*fs/1000)); myGUIdata.windowFunction = nuttallwin(round(myGUIdata.windowLengthInMs*fs/1000)); myGUIdata.windowLengthInSample = length(myGUIdata.windowFunction); myGUIdata.ticLocationList = filterBankStr.ticLocationList; myGUIdata.tickLabelList = filterBankStr.tickLabelList; myGUIdata.dynamicRange = 80; set(myGUIdata.dynamicRangeSlider,'Value',0.2); set(myGUIdata.dynamicRanbeText,'string',[num2str(myGUIdata.dynamicRange,'%3.0f') ' dB']); myGUIdata.maxLevel = -100; end %--- private function for make it wide spectrogram function myGUIdata = settingForWideband(myGUIdata) myGUIdata.windowLengthInMs = 10; myGUIdata.higherFrequencyLimit = 8000; fs = myGUIdata.samplingFrequency; fftl = 2^ceil(log2(myGUIdata.windowLengthInMs*fs/1000)+1); %fftl = 1024; fx = (0:fftl/2)/fftl*fs; fxx = fx(fx<myGUIdata.higherFrequencyLimit); frameShift = 0.0005; tx = 0:frameShift:1; myGUIdata.initialSgramData = rand(length(fxx),length(tx))*62+1; myGUIdata.frameShift = frameShift; myGUIdata.visibleFrequencyAxis = fxx; myGUIdata.timeAxis = tx; myGUIdata.fftl = fftl; myGUIdata.fftBuffer = zeros(fftl,length(tx)); myGUIdata.lastPosition = 1; myGUIdata.frameShiftInSample = round(myGUIdata.frameShift*fs); %myGUIdata.windowFunction = blackman(round(myGUIdata.windowLengthInMs*fs/1000)); myGUIdata.windowFunction = nuttallwin(round(myGUIdata.windowLengthInMs*fs/1000)); myGUIdata.windowLengthInSample = length(myGUIdata.windowFunction); myGUIdata.dynamicRange = 80; set(myGUIdata.dynamicRangeSlider,'Value',0.2); set(myGUIdata.dynamicRanbeText,'string',[num2str(myGUIdata.dynamicRange,'%3.0f') ' dB']); myGUIdata.maxLevel = -100; end function synchDrawGUI(obj, event, string_arg) handleForTimer = get(obj,'userData'); myGUIdata = guidata(handleForTimer); numberOfSamples = myGUIdata.windowLengthInSample; dynamicRange = myGUIdata.dynamicRange; fftl = myGUIdata.fftl; w = myGUIdata.windowFunction; fxx = myGUIdata.visibleFrequencyAxis; fs = myGUIdata.samplingFrequency; if get(myGUIdata.recordObj1,'TotalSamples') > fftl*4 tmpAudio = getaudiodata(myGUIdata.recordObj1); currentPoint = length(tmpAudio); if length(currentPoint-numberOfSamples+1:currentPoint) > 10 set(myGUIdata.counterText,'string',num2str(myGUIdata.audioRecorderCount)); myGUIdata.audioRecorderCount = myGUIdata.audioRecorderCount-1; spectrogramBuffer = get(myGUIdata.sgramHandle,'cdata'); ii = 0; while myGUIdata.lastPosition+myGUIdata.frameShiftInSample+numberOfSamples < currentPoint ii = ii+1; currentIndex = myGUIdata.lastPosition+myGUIdata.frameShiftInSample; x = tmpAudio(currentIndex+(0:numberOfSamples-1)); switch get(myGUIdata.displayPopupMenu,'Value') case {1,2} tmpSpectrum = 20*log10(abs(fft(x.*w,fftl))); case {3,4,5} tmpSpectrum = abs(fft(x.*w,fftl)).^2; end; myGUIdata.fftBuffer(:,ii) = tmpSpectrum; myGUIdata.lastPosition = currentIndex; end; nFrames = ii; if nFrames > 0 tmpSgram = myGUIdata.fftBuffer(:,1:nFrames); switch get(myGUIdata.displayPopupMenu,'Value') case 5 fx = (0:fftl/2)/fftl*fs; filterBankStr = simulatedFilterBank(tmpSgram(1:fftl/2+1,:),fx,'third'); tmpSgram = 10*log10(filterBankStr.filteredSgramTriangle); case 3 fx = (0:fftl/2)/fftl*fs; filterBankStr = simulatedFilterBank(tmpSgram(1:fftl/2+1,:),fx,'ERB'); tmpSgram = 10*log10(filterBankStr.filteredSgramTriangle); case 4 fx = (0:fftl/2)/fftl*fs; filterBankStr = simulatedFilterBank(tmpSgram(1:fftl/2+1,:),fx,'Bark'); tmpSgram = 10*log10(filterBankStr.filteredSgramTriangle); end; if myGUIdata.maxLevel < max(tmpSgram(:)) myGUIdata.maxLevel = max(tmpSgram(:)); else myGUIdata.maxLevel = max(-100,myGUIdata.maxLevel*0.998); end; tmpSgram = 62*max(0,(tmpSgram-myGUIdata.maxLevel)+dynamicRange)/dynamicRange+1; spectrogramBuffer(:,1:end-nFrames) = spectrogramBuffer(:,nFrames+1:end); spectrogramBuffer(:,end-nFrames+1:end) = tmpSgram(1:length(fxx),:); set(myGUIdata.sgramHandle,'cdata',spectrogramBuffer); else disp('no data read!'); end; else disp('overrun!') end; if myGUIdata.audioRecorderCount < 0 switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end disp('Initilizing audio buffer'); stop(myGUIdata.recordObj1); record(myGUIdata.recordObj1); myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.lastPosition = 1; switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); end end; guidata(handleForTimer,myGUIdata); else disp(['Recorded data is not enough! Skipping this interruption....at ' datestr(now,30)]); end; end % --- Outputs from this function are returned to the command line. function varargout = realtimeSpectrogramV3_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; end % --- Executes on button press in startButton. function startButton_Callback(hObject, eventdata, handles) % hObject handle to startButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.realTimeSgramGUI); set(myGUIdata.saveButton,'enable','off'); set(myGUIdata.startButton,'enable','off'); set(myGUIdata.playButton,'enable','off'); set(myGUIdata.stopButton,'enable','on'); set(myGUIdata.displayPopupMenu,'enable','off'); switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms); end myGUIdata.audioRecorderCount = myGUIdata.maxAudioRecorderCount; myGUIdata.lastPosition = 1; record(myGUIdata.recordObj1); switch get(myGUIdata.timer50ms,'running') case 'off' start(myGUIdata.timer50ms); case 'on' otherwise disp('timer is bloken!'); end guidata(handles.realTimeSgramGUI,myGUIdata); end % --- Executes on button press in stopButton. function stopButton_Callback(hObject, eventdata, handles) % hObject handle to stopButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.realTimeSgramGUI); set(myGUIdata.saveButton,'enable','on'); set(myGUIdata.startButton,'enable','on'); set(myGUIdata.playButton,'enable','on'); set(myGUIdata.stopButton,'enable','off'); set(myGUIdata.displayPopupMenu,'enable','on'); switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) case 'off' otherwise disp('timer is bloken!'); end; myGUIdata.audioData = getaudiodata(myGUIdata.recordObj1); stop(myGUIdata.recordObj1); guidata(handles.realTimeSgramGUI,myGUIdata); end % --- Executes on button press in playButton. function playButton_Callback(hObject, eventdata, handles) % hObject handle to playButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.realTimeSgramGUI); x = myGUIdata.audioData; fs = myGUIdata.samplingFrequency; minus4 = max(1,round((length(x)/fs-4)*fs)); sound(x(minus4:end)/max(abs(x(minus4:end)))*0.99,fs); end % --- 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) myGUIdata = guidata(handles.realTimeSgramGUI); outFileName = ['relFFTIn' datestr(now,30) '.wav']; [file,path] = uiputfile(outFileName,'Save the last 4 second data'); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 %okInd = 0; disp('Save is cancelled!'); return; end; end; wavwrite(myGUIdata.audioData,myGUIdata.samplingFrequency,16,[path file]); end % --- Executes on button press in quitButton. function quitButton_Callback(hObject, eventdata, handles) % hObject handle to quitButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) myGUIdata = guidata(handles.realTimeSgramGUI); %disp('timer ends') switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) end; stop(myGUIdata.recordObj1); delete(myGUIdata.timer50ms); delete(myGUIdata.recordObj1); close(handles.realTimeSgramGUI); end % --- Executes on slider movement. function dynamicRangeSlider_Callback(hObject, eventdata, handles) % hObject handle to dynamicRangeSlider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider myGUIdata = guidata(handles.realTimeSgramGUI); value = get(hObject,'Value'); myGUIdata.dynamicRange = max(1,abs((value-1)*100)); set(myGUIdata.dynamicRanbeText,'string',[num2str(myGUIdata.dynamicRange,'%3.0f') ' dB']); guidata(handles.realTimeSgramGUI,myGUIdata); end % --- Executes during object creation, after setting all properties. function dynamicRangeSlider_CreateFcn(hObject, eventdata, handles) % hObject handle to dynamicRangeSlider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end set(hObject,'value',0.2); end % --- Executes on selection change in displayPopupMenu. function displayPopupMenu_Callback(hObject, eventdata, handles) % hObject handle to displayPopupMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns displayPopupMenu contents as cell array % contents{get(hObject,'Value')} returns selected item from displayPopupMenu myGUIdata = guidata(handles.realTimeSgramGUI); %disp('hit!') contents = cellstr(get(hObject,'String')); myGUIdata.displayType = contents{get(hObject,'Value')}; switch get(myGUIdata.timer50ms,'running') case 'on' stop(myGUIdata.timer50ms) case 'off' otherwise disp('timer is bloken!'); end; switch get(hObject,'Value') case 1 myGUIdata = settingForNarrowband(myGUIdata); set(myGUIdata.sgramHandle,'cdata',myGUIdata.initialSgramData*0+1);%, ... set(myGUIdata.sgramHandle,'xdata',[myGUIdata.timeAxis(1) myGUIdata.timeAxis(end)]-myGUIdata.timeAxis(end), ... 'ydata',[myGUIdata.visibleFrequencyAxis(1) myGUIdata.visibleFrequencyAxis(end)]); set(myGUIdata.sgramAxis,'xlim',[myGUIdata.timeAxis(1) myGUIdata.timeAxis(end)]-myGUIdata.timeAxis(end), ... 'ylim',[myGUIdata.visibleFrequencyAxis(1) myGUIdata.visibleFrequencyAxis(end)]); set(myGUIdata.sgramAxis,'ytick',myGUIdata.linearTicLocationList); set(myGUIdata.sgramAxis,'ytickLabel',myGUIdata.linearTickLabelList); set(myGUIdata.titleText,'string','Narrowband spectrogram','fontunit','normalized','fontsize',0.03); enableZoomingTools(myGUIdata); case 2 myGUIdata = settingForWideband(myGUIdata); set(myGUIdata.sgramHandle,'cdata',myGUIdata.initialSgramData*0+1);%, ... set(myGUIdata.sgramHandle,'xdata',[myGUIdata.timeAxis(1) myGUIdata.timeAxis(end)]-myGUIdata.timeAxis(end), ... 'ydata',[myGUIdata.visibleFrequencyAxis(1) myGUIdata.visibleFrequencyAxis(end)]); set(myGUIdata.sgramAxis,'xlim',[myGUIdata.timeAxis(1) myGUIdata.timeAxis(end)]-myGUIdata.timeAxis(end), ... 'ylim',[myGUIdata.visibleFrequencyAxis(1) myGUIdata.visibleFrequencyAxis(end)]); set(myGUIdata.titleText,'string','Wideband spectrogram','fontunit','normalized','fontsize',0.03); set(myGUIdata.sgramAxis,'ytick',myGUIdata.linearTicLocationListWide); set(myGUIdata.sgramAxis,'ytickLabel',myGUIdata.linearTickLabelListWide); enableZoomingTools(myGUIdata); case {3,4,5} myGUIdata = settingForThirdband(myGUIdata); set(myGUIdata.sgramHandle,'cdata',myGUIdata.initialSgramData*0+1);%, ... set(myGUIdata.sgramHandle,'xdata',[myGUIdata.timeAxis(1) myGUIdata.timeAxis(end)]-myGUIdata.timeAxis(end), ... 'ydata',[myGUIdata.visibleFrequencyAxis(1) myGUIdata.visibleFrequencyAxis(end)]); set(myGUIdata.sgramAxis,'xlim',[myGUIdata.timeAxis(1) myGUIdata.timeAxis(end)]-myGUIdata.timeAxis(end), ... 'ylim',[myGUIdata.visibleFrequencyAxis(1) myGUIdata.visibleFrequencyAxis(end)]); %keyboard; set(myGUIdata.sgramAxis,'ytick',myGUIdata.ticLocationList,'yticklabel',myGUIdata.tickLabelList); switch get(hObject,'Value') case 5 set(myGUIdata.titleText,'string','Simulated 1/3 octave band filter, based on 80 ms Nuttallwin','fontunit','normalized','fontsize',0.03); case 3 set(myGUIdata.titleText,'string','Simulated ERB_N filter, based on 80 ms Nuttallwin (temporal resolution is misleading!)','fontunit','normalized','fontsize',0.03); case 4 set(myGUIdata.titleText,'string','Simulated Bark filter, based on 80 ms Nuttallwin (temporal resolution is misleading!)','fontunit','normalized','fontsize',0.03); end; disableZoomingTools(myGUIdata); end get(myGUIdata.sgramHandle) %start(myGUIdata.timer50ms); guidata(handles.realTimeSgramGUI,myGUIdata); startButton_Callback(myGUIdata.startButton, eventdata, handles); end % --- Executes during object creation, after setting all properties. function displayPopupMenu_CreateFcn(hObject, eventdata, handles) % hObject handle to displayPopupMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % ---- private functions function enableZoomingTools(myGUIdata) set(myGUIdata.uitoggletool3,'enable','on'); set(myGUIdata.uitoggletool2,'enable','on'); set(myGUIdata.uitoggletool1,'enable','on'); end function disableZoomingTools(myGUIdata) set(myGUIdata.uitoggletool3,'enable','off'); set(myGUIdata.uitoggletool2,'enable','off'); set(myGUIdata.uitoggletool1,'enable','off'); end
github
HidekiKawahara/SparkNG-master
vtShapeToSoundTestV28.m
.m
SparkNG-master/GUI/vtShapeToSoundTestV28.m
83,654
utf_8
1544b6fc71765702b944121ae08923e2
function varargout = vtShapeToSoundTestV28(varargin) % VTSHAPETOSOUNDTESTV28 MATLAB code for vtShapeToSoundTestV28.fig % VTSHAPETOSOUNDTESTV28, by itself, creates a new VTSHAPETOSOUNDTESTV28 or raises the existing % singleton*. % % H = VTSHAPETOSOUNDTESTV28 returns the handle to a new VTSHAPETOSOUNDTESTV28 or the handle to % the existing singleton*. % % VTSHAPETOSOUNDTESTV28('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in VTSHAPETOSOUNDTESTV28.M with the given input arguments. % % VTSHAPETOSOUNDTESTV28('Property','Value',...) creates a new VTSHAPETOSOUNDTESTV28 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before vtShapeToSoundTestV28_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to vtShapeToSoundTestV28_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 % % Designed and coded by Hideki Kawahara. % http://www.wakayama-u.ac.jp/%7ekawahara/index_e.html % Originally prepared for the World Vioce Day 2015 at Showa, % 18/April/2015. % 28/July/2015 Introduction of L-F model % 30/July/2015 Interaction senario is revised % 01/Aug./2015 bug fix (GUI of L-F model) % 23/Aug./2015 Adjustable GUI % 06/Nov./2015 Out signal display % 15/Nov./2015 Input spectrum display % 16/Dec./2015 Interactive F0 manipulation % Edit the above text to modify the response to help vtShapeToSoundTestV28 % Last Modified by GUIDE v2.5 22-Nov-2015 13:32:09 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @vtShapeToSoundTestV28_OpeningFcn, ... 'gui_OutputFcn', @vtShapeToSoundTestV28_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 end % --- Executes just before vtShapeToSoundTestV28 is made visible. function vtShapeToSoundTestV28_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 vtShapeToSoundTestV28 (see VARARGIN) % Choose default command line output for vtShapeToSoundTestV28 handles.output = hObject; handles.LFDesigner = []; handles.mfilename = mfilename; % setup recorder object handles.audioRecorder = audiorecorder(44100,16,1); handles.maximumRecordCount = 200; handles.audioRecordCount = handles.maximumRecordCount; % Update handles structure guidata(hObject, handles); handles = initialize_display(handles); syncVTL(handles.vtLength,handles); handles.inputSegment = []; handles.monitoredSound = [0;0]; handles.releaseToPlay = get(handles.releaseToPlayEnableRadioButton,'Value'); %hObject %handles % Final stage update handles structure guidata(hObject, handles); set(handles.audioRecorder,'TimerPeriod',0.1,'TimerFcn',{@spectrumMonitor,handles}); %handles %handles synchSource(handles); %guidata(handles.vtTester,handles); % UIWAIT makes vtShapeToSoundTestV28 wait for user response (see UIRESUME) % uiwait(handles.vtTester); end % --- Outputs from this function are returned to the command line. function varargout = vtShapeToSoundTestV28_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; end % --- Executes on button press in SoundItButton. function SoundItButton_Callback(hObject, eventdata, handles) % hObject handle to SoundItButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) soundItBody(handles); end % --- Executes on button press in QuitButton. function QuitButton_Callback(hObject, eventdata, handles) % hObject handle to QuitButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) stop(handles.timer); delete(timerfindall); if ~isempty(handles.LFDesigner) if ishghandle(handles.LFDesigner) close(handles.LFDesigner); end; end; close(handles.vtTester); end function updatedHandles = initialize_display(handles) updatedHandles = handles; updatedHandles.samplingFrequency = 44100; updatedHandles.vtLengthNorimal = 17; % 17 cm updatedHandles.soundSpeed = 35000; % 35000 cm/s at 31 degree centigrade (ref. Story 1996) updatedHandles.nSection = ... ceil(updatedHandles.vtLengthNorimal*2/updatedHandles.soundSpeed*updatedHandles.samplingFrequency); updatedHandles.logArea = zeros(updatedHandles.nSection+1,1); updatedHandles.vtLengthReference = updatedHandles.nSection/2*updatedHandles.soundSpeed/updatedHandles.samplingFrequency; updatedHandles.vtLength = updatedHandles.vtLengthReference; updatedHandles.F0 = 125; fs = updatedHandles.samplingFrequency; c = updatedHandles.soundSpeed; %l = updatedHandles.vtLength; %----- vocal tract drawing pad axes(handles.VTDrawer) maxArea = log(2^8); bottomLvl = log(2^(-1)); updatedHandles.defaultMaxArea = maxArea; updatedHandles.defaultBottomLvl = bottomLvl; updatedHandles.areaFrame = plot([0 18 18 0 0],[bottomLvl bottomLvl maxArea maxArea bottomLvl],'b'); updatedHandles.areaFrameDefaultYdata = [bottomLvl bottomLvl maxArea maxArea bottomLvl]; hold on updatedHandles.vtlHandle = plot([8 8],[bottomLvl-5 maxArea+5],'c','linewidth',3); updatedHandles.vtlHandleOriginalXdata = get(updatedHandles.vtlHandle,'xdata'); xGridHandleList = zeros(35,1); for ii = 1:35 xGridHandleList (ii) = plot([ii ii],[bottomLvl-5 maxArea+5],'b:'); end; updatedHandles.vtDrawerXGridHandleList = xGridHandleList; for ii = -5:12 plot([0 35],[1 1]*log(2^ii),'b:'); end; updatedHandles.logAreaPlotHandle = ... plot(((0:updatedHandles.nSection)+0.5)*c/fs/2,updatedHandles.logArea,'b-o','linewidth',3); updatedHandles.traceBuffer = zeros(1000,2)+NaN; updatedHandles.pointCount = 1; updatedHandles.traceHandle = plot(updatedHandles.traceBuffer(:,1), ... updatedHandles.traceBuffer(:,2),'g-','linewidth',2); updatedHandles.modifierIndicatorHandle = ... plot((0:updatedHandles.nSection)*c/fs/2,updatedHandles.logArea*0+log(16),'color',[0 0.8 0]); updatedHandles.logAreaDeviation = updatedHandles.logArea; set(gca,'fontsize',14); set(gca,'ytick',log(2.0.^(-3:12)),'ytickLabel',{'0.125';'0.25';'0.5';'1';'2';'4'; ... '8';'16';'32';'64';'128';'256';'512';'1024';'2048';'4096'}); set(gca,'xtick',5:5:35,'xtickLabel',{'5';'10';'15';'20';'25';'30';'35'}); updatedHandles.vtDrawerXtick = get(gca,'xtick'); updatedHandles.vtDrawerXtickLabel = get(gca,'xtickLabel'); axis([0 18 bottomLvl maxArea]); xlabel('distance from lip (cm)'); ylabel('relative area'); %------- vocal tract shape modifier axes(handles.modifierAxis); xData = (0:updatedHandles.nSection)'*c/fs/2; xBase = xData/xData(end-1)*pi; yData = zeros(length(xData),7); for ii = 1:3 yData(:,ii*2-1) = sin(ii*xBase); yData(:,ii*2) = cos(ii*xBase); end; yData(:,7) = cos(0*xBase); updatedHandles.modifierComponentHandle = plot(xData+c/fs/2*0.5,yData,'linewidth',2); updatedHandles.modifierBasis = yData; hold on modifierHandleList = [1/2 0 1/4 1 1/6 2/3 3/4]*xData(end-1); compositeModifierShape = sum(yData,2); if max(abs(compositeModifierShape))>1 modifierScalerValue = max(abs(compositeModifierShape)); compositeModifierShapeViewer = compositeModifierShape/modifierScalerValue; else modifierScalerValue = 1; compositeModifierShapeViewer = compositeModifierShape; end; updatedHandles.modifierHandleList = modifierHandleList; updatedHandles.coefficientList = modifierHandleList*0+1; updatedHandles.modifierScalerValue = modifierScalerValue; updatedHandles.modifierHandle = plot(xData+c/fs/2*0.5,compositeModifierShapeViewer,'k','linewidth',4); updatedHandles.modifierTraceBuffer = zeros(1000,2)+NaN; updatedHandles.modifierCount = 1; updatedHandles.modifierTraceBufferHandle = plot(xData++c/fs/2*0.5,compositeModifierShapeViewer+NaN,'g','linewidth',2); %updatedHandles.modifierTraceBufferHandle plot(xData,xData*0,'k'); releaseID = version('-release'); yearID = str2double(releaseID(1:4)); if yearID >= 2015 || strcmp(releaseID,'2014b') set(gca,'colororderindex',1); end; modifierAnchorHandles = zeros(7,1); for ii = 1:7 modifierAnchorHandles(ii) = plot(modifierHandleList(ii)++c/fs/2*0.5,1,'o','linewidth',2); end; updatedHandles.modifierAnchorHandles = modifierAnchorHandles; minorGrid = 0:35; modifierMinorGridList = zeros(length(minorGrid),1); for ii = 1:length(minorGrid) modifierMinorGridList(ii) = plot(minorGrid(ii)*[1 1],[-1.2 1.2],'k:'); end; updatedHandles.minorGrid = minorGrid; updatedHandles.modifierMinorGridList = modifierMinorGridList; majorGrid = 5:5:35; modifierMajorGridList = zeros(length(majorGrid),1); for ii = 1:length(majorGrid) modifierMajorGridList(ii) = plot(majorGrid(ii)*[1 1],[-1.2 1.2],'k-'); end; updatedHandles.majorGrid = majorGrid; updatedHandles.modifierMajorGridList = modifierMajorGridList; axis([0 18 -1.2 1.2]); axis('off'); %axis('off') axes(handles.sliderAxis); updatedHandles.sliderRail = plot([0 0],[-4 4],'b-','linewidth',5); hold on; updatedHandles.magnifierValue = 0; updatedHandles.magnifierKnob = plot(0,0,'b+','linewidth',5,'markersize',18); %updatedHandles.sliderAxis axis('off'); %-------- vocal tract 3D display axes(handles.VT3d) crossSection = exp(updatedHandles.logArea); crossSection = crossSection/max(crossSection); [X,Y,Z] = cylinder(crossSection,40); updatedHandles.tract3D = surf(Z,Y,X); view(-8,12); axis([0 1 [-1 1 -1 1]*1.5]); axis off; axis('vis3d'); vis3dUserData.initialCamereLocation = get(handles.VT3d,'cameraposition'); vis3dUserData.counter = 1; set(handles.VT3d,'userdata',vis3dUserData); %-------- vocal tract frequency domain display [gaindB,fx] = handleToGain(updatedHandles); axes(handles.gainPlot); rootVector = [500 1200;1500 1400;2500 1300;3500 1200;4500 1500]; [ax,h1,h2] = plotyy(fx,gaindB,rootVector(:,1),-log10(rootVector(:,2)));%'linewidth',2,... %,'linewidth',2);grid on; updatedHandles.gainPlotHandle = h1; updatedHandles.rootsPlotHandle = h2; updatedHandles.gainRootAxis = ax; maxGain = max(gaindB(fx<5000)); %axis([0 5000 maxGain+[-60 5]]); set(ax(1),'xlim',[0 5000],'ylim',maxGain+[-80 5]); set(ax(1),'fontsize',13,'ytick',-70:10:60,'xgrid','on','ygrid','on'); set(ax(1),'xtick',[1000:1000:10000],'xtickLabel',{'1';'2';'3';'4';'5';... '6';'7';'8';'9';'10'}); updatedHandles.gainRootAxisXtick = get(ax(1),'xtick'); updatedHandles.gainRootAxisXtickLabel = get(ax(1),'xtickLabel'); set(ax(2),'xlim',[0 5000],'ylim',-log10([1100 1])); set(ax(2),'fontsize',13,'ytick',-log10([2000 1000 700 500 300 200 100 70 50 30 20 10 7 5 3 2 1]), ... 'yticklabel',{'2000';'1000';' ';'500';' ';'200';'100';' ';'50';' ';'20';'10';' ';'5';' ';'2';'1'}); set(h1,'linewidth',2); set(h2,'linestyle','none','marker','o','linewidth',2); xlabel('frequency (kHz)'); ylabel('Gain (dB)'); axes(ax(1)); hold on; maxDisplayHarmonics = round(10000/40/4)*4; updatedHandles.harmonicAxis = reshape(cumsum(ones(maxDisplayHarmonics,2))',maxDisplayHarmonics*2,1); updatedHandles.harmonicLines = reshape([-ones(maxDisplayHarmonics/2,1) ones(maxDisplayHarmonics/2,1) ... ones(maxDisplayHarmonics/2,1) -ones(maxDisplayHarmonics/2,1)]',maxDisplayHarmonics*2,1); updatedHandles.harmonicsHandle = ... plot(updatedHandles.harmonicAxis*updatedHandles.F0,100*updatedHandles.harmonicLines,'c'); set(updatedHandles.harmonicsHandle,'zdata',updatedHandles.harmonicAxis*0-1); h3 = plot(fx,gaindB*0,'r'); updatedHandles.outSpectrumHandle = h3; h4 = plot(fx,gaindB*0+2,'color',[0 0.7 0]); updatedHandles.totalEnvelopeHandle = h4; h5 = plot(fx,gaindB*0+4,'k'); updatedHandles.inSpectrumHandle = h5; axes(ax(2)); ylabel('bandwidth (Hz)'); hold on; updatedHandles.poleMarker = plot(500,-log10(2000),'g+','markersize',23,'linewidth',5); lsfList = 10000+(1:updatedHandles.nSection); lsfMark = [-100*ones(1,length(lsfList));100*ones(1,length(lsfList))]; updatedHandles.lsfHandle = plot([lsfList;lsfList],lsfMark,'b--','linewidth',1); %cameraLocation = get(handles.VT3d,'cameraposition'); %cameraLocation %rotate3d(handles.VT3d); %----- define pointer shape data for pen updatedHandles = definePenPointerShape(updatedHandles); updatedHandles = definePickerPointerShape(updatedHandles); updatedHandles = defineLRPointerShape(updatedHandles); %----- handlear assignement set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.vtTester,'windowbuttonDownFcn',@MousebuttonDown); set(handles.frequencyValue,'visible','off'); set(handles.bandWidthValue,'visible','off'); set(handles.frequencyTitleText,'visible','off'); set(handles.bandWidthTitleText,'visible','off'); set(updatedHandles.outSpectrumHandle,'visible','off'); set(updatedHandles.totalEnvelopeHandle,'visible','off'); set(updatedHandles.inSpectrumHandle,'visible','off'); set(updatedHandles.harmonicsHandle,'visible','off'); set(handles.SoundMonitorPanel,'visible','off'); set(handles.stopMonitorButton,'visible','off'); set(handles.startMonitorButton,'visible','off'); set(handles.audioCounterText,'visible','off'); set(handles.playMonitorButton,'visible','off'); updatedHandles.timer = timer('period',0.1,'timerFcn',{@rotateCamera,handles},'executionmode','fixedrate'); %set(handles.vtTester,'userdata',updatedHandles); start(updatedHandles.timer); set(handles.SaveButton,'enable','off'); %----- source information preparation updatedHandles.durationList = [0.25 0.5 1 2 4]; updatedHandles.duration = 1; set(handles.durationPopup,'value',3); updatedHandles.vibratoDepth = 50; updatedHandles.vibratoFrequency = 5.5; updatedHandles.variableF0 = 'off'; updatedHandles = defaultLFparameters(updatedHandles); set(handles.voiceQualityPopup,'visible','on'); end function updatedHandles = defaultLFparameters(updatedHandles) updatedHandles.LFparametersBaseSet = ... [0.4134 0.5530 0.0041 0.5817; ... 0.4808 0.5955 0.0269 0.7200; ... 0.4621 0.6604 0.0270 0.7712]; updatedHandles.LFparameterNames = {'modal';'fry';'breathy'}; updatedHandles.currentVQName = char(updatedHandles.LFparameterNames{1}); LFparameters = struct; LFparameters.tp = updatedHandles.LFparametersBaseSet(1,1); LFparameters.te = updatedHandles.LFparametersBaseSet(1,2); LFparameters.ta = updatedHandles.LFparametersBaseSet(1,3); LFparameters.tc = updatedHandles.LFparametersBaseSet(1,4); updatedHandles.LFparameters = LFparameters; updatedHandles.LFDesigner = []; %--- equalizer design %cosineCoefficient = [0.355768 0.487396 0.144232 0.012604]; % Nuttall win12 %upperLimit = 50; %halfSample = 50; hc = [0.2624710164 0.4265335164 0.2250165621 0.0726831633 0.0125124215 0.0007833203]; updatedHandles.equalizerStr = equalizerDesignAAFX(hc, 68, 80, 1.5); %updatedHandles.equalizerStr = equalizerDesignAAFX(cosineCoefficient,upperLimit,halfSample, 1.5); end function rotateCamera(src,evnt,handles) cameraLocation = get(handles.VT3d,'cameraposition'); vis3dUserData = get(handles.VT3d,'userdata'); vis3dUserData.counter = vis3dUserData.counter+1; deltaRotation = exp(1i*pi*0.03*sin(vis3dUserData.counter/50*2*pi)); xyComplex = vis3dUserData.initialCamereLocation(1)+1i*vis3dUserData.initialCamereLocation(2); newCameraLocation = cameraLocation; newCameraLocation(1) = real(xyComplex*deltaRotation); newCameraLocation(2) = imag(xyComplex*deltaRotation); set(handles.VT3d,'cameraposition',newCameraLocation); set(handles.VT3d,'userdata',vis3dUserData); %guidata(handles.vtTester,handles); end function MousebuttonDown(src,evnt) handles = guidata(src); pointerShape = get(handles.vtTester,'pointer'); %pointerShape %switch pointerShape % case 'cross' if isInsideAxis(handles.VTDrawer) %disp('hit m d') if strcmp(pointerShape,'hand') handles.initialLocation = get(handles.VTDrawer,'currentPoint'); set(handles.vtTester,'WindowButtonMotionFcn',@moveVTLWhileMouseDown); set(handles.vtTester,'windowbuttonUpFcn',@penUpVTLFunction); set(handles.vtTester,'pointer','custom','pointerShapeCData',handles.pointerShapeCDataForLR, ... 'pointerShapeHotSpot',handles.hotSpotForLR); set(handles.vtlHandle,'linewidth',5); guidata(src,handles); else handles.initialLocation = get(handles.VTDrawer,'currentPoint'); handles.pointCount = 1; handles.traceBuffer = handles.traceBuffer+NaN; handles.traceBuffer(handles.pointCount,:) = handles.initialLocation(1,1:2); set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseDown); set(handles.vtTester,'windowbuttonUpFcn',@penUpFunction); set(handles.vtTester,'pointer','custom','pointerShapeCData',handles.pointerShapeCDataForPen, ... 'pointerShapeHotSpot',handles.hotSpotForPen); guidata(src,handles); end; % case 'hand' elseif isInsideAxis(handles.gainRootAxis(2)) && strcmp(pointerShape,'hand') currentPoint = get(handles.gainRootAxis(2),'currentPoint'); xLimit = get(handles.gainRootAxis(2),'xlim'); yLimit = get(handles.gainRootAxis(2),'ylim'); proxiIndStr = proximityCheck(handles,currentPoint,xLimit,yLimit); fs = handles.samplingFrequency; xData = get(handles.rootsPlotHandle,'xdata'); yData = 10.0.^(-get(handles.rootsPlotHandle,'ydata')); r = exp(-yData/fs*pi).*exp(1i*xData/fs*2*pi); [minV,minIndex] = min(abs(r(proxiIndStr.minIndex)-conj(r))); handles.selectedPair = [proxiIndStr.minIndex minIndex]; vtl = handles.vtLength; set(handles.frequencyValue,'string', ... num2str(xData(proxiIndStr.minIndex)/vtl*handles.vtLengthReference,'%6.1f')); set(handles.bandWidthValue,'string',... num2str(yData(proxiIndStr.minIndex)/vtl*handles.vtLengthReference,'%6.1f')); handles.lastFrequencyValue = xData(proxiIndStr.minIndex); handles.lastBandWidthValue = yData(proxiIndStr.minIndex); set(handles.poleMarker,'xdata',handles.lastFrequencyValue, ... 'ydata',-log10(handles.lastBandWidthValue),'visible','on'); handles.roots = r; set(handles.vtTester,'WindowButtonMotionFcn',@moveRootsWhileMouseDown); set(handles.vtTester,'windowbuttonUpFcn',@penUpForRootsFunction); %set(src,'Pointer','crosshair'); set(handles.vtTester,'pointer','custom','pointerShapeCData',handles.pointerShapeCDataForPicker, ... 'pointerShapeHotSpot',handles.hotSpotForPicker); set(handles.frequencyValue,'visible','on'); set(handles.bandWidthValue,'visible','on'); set(handles.frequencyTitleText,'visible','on'); set(handles.bandWidthTitleText,'visible','on'); guidata(src,handles); elseif isInsideAxis(handles.sliderAxis) && strcmp(pointerShape,'hand') set(handles.magnifierKnob,'color',[0 0.8 0]) set(handles.sliderRail,'color',[0 0.8 0]) set(handles.vtTester,'WindowButtonMotionFcn',@moveSliderWhileMouseDown); set(handles.vtTester,'windowbuttonUpFcn',@penUpForSliderFunction); elseif isInsideAxis(handles.modifierAxis) && strcmp(pointerShape,'hand') set(handles.modifierAnchorHandles(handles.selectedMarkerIndex),'linewidth',5) set(handles.modifierComponentHandle(handles.selectedMarkerIndex),'linewidth',5) set(handles.vtTester,'WindowButtonMotionFcn',@moveModifierComponentWhileMouseDown); set(handles.vtTester,'windowbuttonUpFcn',@penUpForModifierComponentFunction); elseif isInsideAxis(handles.modifierAxis) && strcmp(pointerShape,'crosshair') set(handles.vtTester,'pointer','custom','pointerShapeCData',handles.pointerShapeCDataForPen, ... 'pointerShapeHotSpot',handles.hotSpotForPen); set(handles.vtTester,'WindowButtonMotionFcn',@moveModifierPenWhileMouseDown); set(handles.vtTester,'windowbuttonUpFcn',@penUpForModifierPenFunction); currentPoint = get(handles.modifierAxis,'currentPoint'); handles.modifierCount = 1; handles.modifierTraceBuffer(handles.modifierCount,:) = currentPoint(1,1:2); set(handles.modifierTraceBufferHandle,'xdata',handles.modifierTraceBuffer(1:handles.modifierCount,1), ... 'ydata',handles.modifierTraceBuffer(1:handles.modifierCount,2)); guidata(src,handles); end end function moveVTLWhileMouseDown(src,evnt) handles = guidata(src); currentPoint = get(handles.VTDrawer,'currentPoint'); set(handles.vtlHandle,'xdata',currentPoint(1,1)*[1 1]); vtl = 8/currentPoint(1,1)*handles.vtLengthReference; if abs(vtl) < 8;vtl = 8;end; if abs(vtl) > 35;vtl = 35;end; syncVTL(vtl,handles); handles.vtLength = vtl; guidata(src,handles); end function penUpVTLFunction(src,evnt) handles = guidata(src); set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.vtTester,'windowbuttonUpFcn',''); set(src,'Pointer','hand'); set(handles.vtlHandle,'linewidth',3); set(handles.totalEnvelopeHandle,'linewidth',1); guidata(src,handles); if handles.releaseToPlay soundItBody(handles) end; end function moveModifierPenWhileMouseDown(src,evnt) handles = guidata(src); currentPoint = get(handles.modifierAxis,'currentPoint'); handles.modifierCount = handles.modifierCount+1; handles.modifierTraceBuffer(handles.modifierCount,:) = currentPoint(1,1:2); set(handles.modifierTraceBufferHandle,'xdata',handles.modifierTraceBuffer(1:handles.modifierCount,1), ... 'ydata',handles.modifierTraceBuffer(1:handles.modifierCount,2)); guidata(src,handles); end function penUpForModifierPenFunction(src,evnt) handles = guidata(src); set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.vtTester,'windowbuttonUpFcn',''); xData = get(handles.modifierHandle,'xdata'); yData = get(handles.modifierHandle,'ydata'); [orderededPoints,sortIndex] = sort(handles.modifierTraceBuffer(1:handles.modifierCount,1)); orderedValue = handles.modifierTraceBuffer(sortIndex,2); orderededPoints = orderededPoints(:)+cumsum(ones(handles.modifierCount,1))/10000; indexList = 1:length(xData); boundaryIndex = interp1(xData,indexList,[orderededPoints(1) orderededPoints(end)],'linear','extrap'); boundaryIndex(1) = max(1,ceil(boundaryIndex(1))); boundaryIndex(2) = min(length(xData),floor(boundaryIndex(2))); segmentValue = interp1(orderededPoints,orderedValue,xData(boundaryIndex(1):boundaryIndex(2)), ... 'linear','extrap'); yData(boundaryIndex(1):boundaryIndex(2)) = segmentValue; set(handles.modifierHandle,'ydata',yData); handles.modifierTraceBuffer = handles.modifierTraceBuffer+NaN; set(handles.modifierTraceBufferHandle,'xdata',handles.modifierTraceBuffer(1:handles.modifierCount,1), ... 'ydata',handles.modifierTraceBuffer(1:handles.modifierCount,2)); set(src,'Pointer','crosshair'); set(handles.modifierIndicatorHandle,'ydata',yData*handles.magnifierValue+log(16)); handles.logArea = get(handles.logAreaPlotHandle,'ydata'); handles.logAreaDeviation = handles.logArea(:)-yData(:)*handles.magnifierValue; handles.modifierCount = 1; updatePlots(handles); set(handles.SaveButton,'enable','off'); guidata(src,handles); if handles.releaseToPlay soundItBody(handles) end; end function penUpForModifierComponentFunction(src,evnt) handles = guidata(src); set(handles.modifierAnchorHandles(handles.selectedMarkerIndex),'linewidth',2) set(handles.modifierComponentHandle(handles.selectedMarkerIndex),'linewidth',2) set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.vtTester,'windowbuttonUpFcn',''); set(handles.SaveButton,'enable','off'); guidata(src,handles); set(handles.SaveButton,'enable','off'); if handles.releaseToPlay soundItBody(handles) end; end function moveModifierComponentWhileMouseDown(src,evnt) handles = guidata(src); currentPoint = get(handles.modifierAxis,'currentPoint'); handles.coefficientList(handles.selectedMarkerIndex) = currentPoint(1,2); set(handles.modifierAnchorHandles(handles.selectedMarkerIndex),'ydata',currentPoint(1,2)); set(handles.modifierComponentHandle(handles.selectedMarkerIndex),'ydata',... handles.modifierBasis(:,handles.selectedMarkerIndex)*currentPoint(1,2)); modifierValue = handles.modifierBasis*handles.coefficientList(:); if max(abs(modifierValue)) > 1 modifierValue = modifierValue/max(abs(modifierValue)); end; set(handles.modifierHandle,'ydata',modifierValue); set(handles.modifierIndicatorHandle,'ydata',modifierValue*handles.magnifierValue+log(16)); handles.logArea = handles.logAreaDeviation(:)+modifierValue(:)*handles.magnifierValue; handles.logArea(end) = 0; set(handles.logAreaPlotHandle,'ydata',handles.logArea); updatePlots(handles) guidata(src,handles); end function moveSliderWhileMouseDown(src,evnt) handles = guidata(src); currentPoint = get(handles.sliderAxis,'currentPoint'); set(handles.magnifierKnob,'ydata',max(-4,min(4,currentPoint(1,2)))); handles.magnifierValue = max(-4,min(4,currentPoint(1,2))); ydata = get(handles.modifierHandle,'ydata'); set(handles.modifierIndicatorHandle,'ydata',ydata*handles.magnifierValue+log(16)); handles.logArea = handles.logAreaDeviation(:)+ydata(:)*handles.magnifierValue; handles.logArea(end) = 0; %set(handles.logAreaPlotHandle,'ydata',handles.logArea); updatePlots(handles); guidata(src,handles); end function penUpForSliderFunction(src,evnt) handles = guidata(src); set(handles.magnifierKnob,'color','b') set(handles.sliderRail,'color','b') set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.vtTester,'windowbuttonUpFcn',''); guidata(src,handles); set(handles.SaveButton,'enable','off'); if handles.releaseToPlay soundItBody(handles) end; end function moveRootsWhileMouseDown(src,evnt) handles = guidata(src); currentPoint = get(handles.gainRootAxis(2),'currentPoint'); frequency = currentPoint(1,1); bandWidth = 10.0.^(-currentPoint(1,2)); handles = updateParametersFromRoots(handles,frequency,bandWidth); %----- log area plot logAreaPlot(handles); %------ crossSection = exp(handles.logArea); crossSection = crossSection/max(crossSection); [X,Y,Z] = cylinder(crossSection,40); set(handles.tract3D,'xdata',Z,'ydata',Y,'zdata',X); handles.lastFrequency = frequency; handles.lastBandWidth = bandWidth; guidata(src,handles); end function handles = updateParametersFromRoots(handles,frequency,bandWidth) fs = handles.samplingFrequency; currentR = exp(-bandWidth/fs*pi).*exp(1i*frequency/fs*2*pi); vtl = handles.vtLength; set(handles.frequencyValue,'string',num2str(frequency/vtl*handles.vtLengthReference,'%6.1f')); set(handles.bandWidthValue,'string',num2str(bandWidth/vtl*handles.vtLengthReference,'%6.1f')); rootVector = handles.roots; %size(rootVector) rootVector(handles.selectedPair(1)) = currentR; rootVector(handles.selectedPair(2)) = conj(currentR); xData = get(handles.rootsPlotHandle,'xdata'); yData = get(handles.rootsPlotHandle,'ydata'); xData(handles.selectedPair(1)) = frequency;%currentPoint(1,1); xData(handles.selectedPair(2)) = -frequency;%currentPoint(1,1); yData(handles.selectedPair(1)) = -log10(bandWidth);%currentPoint(1,2); yData(handles.selectedPair(2)) = -log10(bandWidth);%currentPoint(1,2); set(handles.rootsPlotHandle,'xdata',xData); set(handles.rootsPlotHandle,'ydata',yData); set(handles.poleMarker,'xdata',frequency,'ydata',-log10(bandWidth),'visible','on'); predictorOrginal = poly(rootVector); predictorTmp = real(predictorOrginal); [gaindB,fx,logArea] = predictorToGain(handles,predictorTmp); set(handles.gainPlotHandle,'ydata',gaindB,'xdata',fx); % Start modification: 10/Nov./2015 if ~isempty(handles.LFDesigner) && ishghandle(handles.LFDesigner) lfDesignerGUIdata = guidata(handles.LFDesigner); if isfield(handles,'F0') %disp('F0 exist') f0Base = handles.F0; else f0Base = 125; end modelFaxis = fx;%get(handles.gainPlotHandle,'xdata'); modelVTgain = gaindB;%get(handles.gainPlotHandle,'ydata'); if isfield(lfDesignerGUIdata,'LFmodelGenericSpectrum') sourceSpectrum = lfDesignerGUIdata.LFmodelGenericSpectrum; levelAtF0 = interp1(lfDesignerGUIdata.LFmodelGenericFaxis,sourceSpectrum,1); sourceGain = interp1(lfDesignerGUIdata.LFmodelGenericFaxis*f0Base,sourceSpectrum-levelAtF0,modelFaxis,'linear','extrap'); set(handles.totalEnvelopeHandle,'visible','on',... 'xdata',modelFaxis,'ydata',modelVTgain(:)+sourceGain(:)); envelopeSpec = modelVTgain(:)+sourceGain(:); maxEnvelope = max(envelopeSpec(modelFaxis<5000)); switch get(handles.inSpectrumHandle,'visible') case 'on' inputSpecData = get(handles.inSpectrumHandle,'ydata'); inputSpecFAxis = get(handles.inSpectrumHandle,'xdata'); maxInputSpec = max(inputSpecData(inputSpecFAxis<5000)); set(handles.inSpectrumHandle,'ydata',inputSpecData-maxInputSpec+maxEnvelope); end; end; end;% End of modification: 10/Nov./2015 maxGain = max(gaindB(fx<5000)); set(handles.gainPlot,'ylim',maxGain+[-70 5]); handles.roots = rootVector; handles.logArea = logArea(:); yData = get(handles.modifierIndicatorHandle,'ydata'); handles.logAreaDeviation = handles.logArea-(yData(:)-log(16)); lsfVector = handleToLsf(handles); for ii = 1:length(lsfVector<5000) set(handles.lsfHandle(ii),'xdata',[lsfVector(ii) lsfVector(ii)], ... 'ydata',[-100 100]); end; end function logAreaPlot(handles) set(handles.logAreaPlotHandle,'ydata',handles.logArea); areaFrameYdata = get(handles.areaFrame,'ydata'); if max(handles.logArea) > handles.defaultMaxArea areaFrameYdata(3:4) = max(handles.logArea); else areaFrameYdata(3:4) = handles.defaultMaxArea; end; if min(handles.logArea) < handles.defaultBottomLvl areaFrameYdata([1 2 5]) = min(handles.logArea); else areaFrameYdata([1 2 5]) = handles.defaultBottomLvl; end; set(handles.areaFrame,'ydata',areaFrameYdata); set(handles.VTDrawer,'ylim',[areaFrameYdata(1) areaFrameYdata(3)]); end function [gaindB,fx,logArea] = predictorToGain(handles,predictorTmp) fs = handles.samplingFrequency; alp = predictorTmp; fftl = 32768; x = zeros(fftl,1); x(1) = 1; y = filter(1,alp,x); gaindB = 20*log10(abs(fft(y))); gaindB = gaindB-gaindB(1); fx = (0:fftl-1)/fftl*fs; k = zalp2k(alp); logArea = log(zref2area(k)); end function k = zalp2k(alp) n = length(alp(2:end)); a = -alp(2:end); b = a*0; k = zeros(n,1); for ii = n:-1:1 k(ii) = a(ii); for jj = 1:ii-1 b(jj) = (a(jj)+k(ii)*a(ii-jj))/(1-k(ii)*k(ii)); end; a = b; end; end function s = zref2area(k) n = length(k); s = zeros(n+1,1); s(end) = 1; for ii = n:-1:1 s(ii) = s(ii+1)*(1-k(ii))/(1+k(ii)); end; end function penUpForRootsFunction(src,evnt) handles = guidata(src); set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.vtTester,'windowbuttonDownFcn',@MousebuttonDown); set(handles.vtTester,'windowbuttonUpFcn',''); set(src,'Pointer','hand'); %set(handles.frequencyValue,'visible','off'); %set(handles.bandWidthValue,'visible','off'); %set(handles.frequencyTitleText,'visible','off'); %set(handles.bandWidthTitleText,'visible','off'); guidata(src,handles); set(handles.SaveButton,'enable','off'); if handles.releaseToPlay soundItBody(handles) end; end function moveWhileMouseDown(src,evnt) handles = guidata(src); [nRow,nColumn] = size(handles.traceBuffer); handles.pointCount = min(nRow,handles.pointCount+1); currentPoint = get(handles.VTDrawer,'currentPoint'); handles.traceBuffer(handles.pointCount,:) = currentPoint(1,1:2); set(handles.traceHandle,'xdata',handles.traceBuffer(:,1),'ydata',handles.traceBuffer(:,2)); guidata(src,handles); end function penUpFunction(src,evnt) handles = guidata(src); set(handles.vtTester,'WindowButtonMotionFcn',@moveWhileMouseUp); set(handles.vtTester,'windowbuttonDownFcn',@MousebuttonDown); set(handles.vtTester,'windowbuttonUpFcn',''); tmpAreaCoordinate = handles.traceBuffer(1:handles.pointCount,:); handles.traceBuffer = handles.traceBuffer+NaN; [sortedX,sortIndex] = sort(tmpAreaCoordinate(:,1)); sortedY = tmpAreaCoordinate(sortIndex,2); finalIndex = 1; trimmedAreaCoordinate = tmpAreaCoordinate*0; trimmedAreaCoordinate(1,:) = [sortedX(1) sortedY(1)]; lastX = sortedX(1); for ii = 2:handles.pointCount if lastX ~= sortedX(ii) finalIndex = finalIndex+1; trimmedAreaCoordinate(finalIndex,:) = [sortedX(ii) sortedY(ii)]; lastX = sortedX(ii); end; end; trimmedAreaCoordinate = trimmedAreaCoordinate(1:finalIndex,:); set(handles.traceHandle,'xdata',trimmedAreaCoordinate(:,1),'ydata',trimmedAreaCoordinate(:,2)+NaN); minX = trimmedAreaCoordinate(1,1); maxX = trimmedAreaCoordinate(end,1); xData = get(handles.logAreaPlotHandle,'xdata'); if minX < xData(2)/2 minX = -1; end; baseIndex = (1:length(xData))'; segmentedIndex = baseIndex(xData>minX & xData < maxX); areaUpdator = interp1(trimmedAreaCoordinate(:,1),trimmedAreaCoordinate(:,2),xData(segmentedIndex), ... 'linear','extrap'); handles.logArea(segmentedIndex) = areaUpdator(:); handles.logArea(end) = 0; set(src,'Pointer','cross'); yData = get(handles.modifierIndicatorHandle,'ydata'); handles.logAreaDeviation = handles.logArea(:)-(yData(:)-log(16)); guidata(src,handles); set(handles.SaveButton,'enable','off'); updatePlots(handles); if handles.releaseToPlay soundItBody(handles) end; end function moveWhileMouseUp(src,evnt) handles = guidata(src); if isInsideAxis(handles.VTDrawer) currentPoint = get(handles.VTDrawer,'currentPoint'); vtlHandleXdata = get(handles.vtlHandle,'xdata'); if abs(currentPoint(1,1)-vtlHandleXdata(1))<0.2 set(src,'Pointer','hand'); else set(src,'Pointer','cross'); end; set(handles.frequencyValue,'visible','off'); set(handles.bandWidthValue,'visible','off'); set(handles.frequencyTitleText,'visible','off'); set(handles.bandWidthTitleText,'visible','off'); set(handles.poleMarker,'visible','off'); else currentPoint = get(handles.gainRootAxis(2),'currentPoint'); xLimit = get(handles.gainRootAxis(2),'xlim'); yLimit = get(handles.gainRootAxis(2),'ylim'); if isInsideAxis(handles.gainRootAxis(2)) proxiIndStr = proximityCheck(handles,currentPoint,xLimit,yLimit); if proxiIndStr.proxiInd == 1 set(src,'Pointer','hand'); else set(src,'Pointer','circle'); end; elseif isInsideAxis(handles.modifierAxis) || isInsideAxis(handles.sliderAxis) set(handles.frequencyValue,'visible','off'); set(handles.bandWidthValue,'visible','off'); set(handles.frequencyTitleText,'visible','off'); set(handles.bandWidthTitleText,'visible','off'); set(handles.poleMarker,'visible','off'); if isCloseToSliderMarker(handles) set(src,'Pointer','hand'); elseif isCloseToModifierMarker(handles) set(src,'Pointer','hand'); else set(src,'Pointer','crosshair'); end; else set(src,'Pointer','arrow'); end; end; end function isCloseInd = isCloseToModifierMarker(handles) isCloseInd = false; currentPoint = get(handles.modifierAxis,'currentPoint'); xLimit = get(handles.modifierAxis,'xlim'); %yLimit = get(handles.sliderAxis,'ylim'); distanceInModifier = zeros(length(handles.modifierAnchorHandles),1); for ii = 1:length(handles.modifierAnchorHandles) xData = get(handles.modifierAnchorHandles(ii),'xdata'); yData = get(handles.modifierAnchorHandles(ii),'ydata'); distanceInModifier(ii) = sqrt(((currentPoint(1,1)-xData)/diff(xLimit)*6)^2+(currentPoint(1,2)-yData)^2); end; [minimumDistance,selectedIndex] = min(distanceInModifier); if minimumDistance < 0.1 isCloseInd = true; handles.selectedMarkerIndex = selectedIndex; guidata(handles.vtTester,handles) end; end function isCloseInd = isCloseToSliderMarker(handles) isCloseInd = false; currentPoint = get(handles.sliderAxis,'currentPoint'); %xLimit = get(handles.sliderAxis,'xlim'); %yLimit = get(handles.sliderAxis,'ylim'); xData = get(handles.magnifierKnob,'xdata'); yData = get(handles.magnifierKnob,'ydata'); distanceInSlider = sqrt((currentPoint(1,1)-xData)^2+(currentPoint(1,2)-yData)^2); if distanceInSlider < 0.2 isCloseInd = true; end; end function proxiIndStr = proximityCheck(handles,currentPoint,xLimit,yLimit) proxiIndStr = struct; proxiIndStr.proxiInd = 0; xData = get(handles.rootsPlotHandle,'xdata'); yData = get(handles.rootsPlotHandle,'ydata'); distanceVector = sqrt(((xData-currentPoint(1,1))/diff(xLimit)*2).^2+ ... ((yData-currentPoint(1,2))/diff(yLimit)).^2); [minDist,minIndex] = min(distanceVector); if minDist<0.02 proxiIndStr.proxiInd = 1; proxiIndStr.minIndex = minIndex; end; end % --- Executes on button press in ResetButton. function ResetButton_Callback(hObject, eventdata, handles) % hObject handle to ResetButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) nSection = length(handles.logArea); handles.logArea = zeros(nSection,1); handles.logArea(end) = 0; ydata = get(handles.modifierIndicatorHandle,'ydata'); handles.logAreaDeviation(:) = handles.logArea(:)-ydata(:); set(handles.totalEnvelopeHandle,'linewidth',1); guidata(handles.vtTester, handles); updatePlots(handles) end %---- private function function updatePlots(handles) %set(handles.logAreaPlotHandle,'ydata',handles.logArea); logAreaPlot(handles); yData = get(handles.modifierIndicatorHandle,'ydata'); handles.logAreaDeviation = handles.logArea(:)-(yData(:)-log(16)); crossSection = exp(handles.logArea); crossSection = crossSection/max(crossSection); [X,Y,Z] = cylinder(crossSection,40); set(handles.tract3D,'xdata',Z,'ydata',Y,'zdata',X); [gaindB,fx] = handleToGain(handles); set(handles.gainPlotHandle,'ydata',gaindB,'xdata',fx); maxGain = max(gaindB(fx<5000)); set(handles.gainPlot,'ylim',maxGain+[-80 5]); rootVector = handleToRoots(handles); set(handles.rootsPlotHandle,'xdata',rootVector(:,1), ... 'ydata',-log10(rootVector(:,2))); lsfVector = handleToLsf(handles); for ii = 1:length(lsfVector<5000) set(handles.lsfHandle(ii),'xdata',[lsfVector(ii) lsfVector(ii)], ... 'ydata',[-100 100]); end; if ~isempty(handles.LFDesigner) && ishghandle(handles.LFDesigner) lfDesignerGUIdata = guidata(handles.LFDesigner); if isfield(handles,'F0') %disp('F0 exist') f0Base = handles.F0; else f0Base = 125; end modelFaxis = get(handles.gainPlotHandle,'xdata')/handles.vtLength*handles.vtLengthReference; modelVTgain = get(handles.gainPlotHandle,'ydata'); if isfield(lfDesignerGUIdata,'LFmodelGenericSpectrum') sourceSpectrum = lfDesignerGUIdata.LFmodelGenericSpectrum; levelAtF0 = interp1(lfDesignerGUIdata.LFmodelGenericFaxis,sourceSpectrum,1); sourceGain = interp1(lfDesignerGUIdata.LFmodelGenericFaxis*f0Base,sourceSpectrum-levelAtF0,... modelFaxis*handles.vtLengthReference/handles.vtLength,'linear','extrap'); scaledVTgain = interp1(modelFaxis/handles.vtLengthReference*handles.vtLength,modelVTgain,modelFaxis,'linear','extrap'); set(handles.totalEnvelopeHandle,'visible','on',... 'xdata',modelFaxis,'ydata',scaledVTgain(:)+sourceGain(:)); %ylim = get(handles.gainRootAxis(1),'ylim'); envelopeSpec = get(handles.totalEnvelopeHandle,'ydata'); envelopeFaxis = get(handles.totalEnvelopeHandle,'xdata'); maxEnvelope = max(envelopeSpec(envelopeFaxis<5000)); switch get(handles.inSpectrumHandle,'visible') case 'on' inputSpecData = get(handles.inSpectrumHandle,'ydata'); inputSpecFAxis = get(handles.inSpectrumHandle,'xdata'); maxInputSpec = max(inputSpecData(inputSpecFAxis<5000)); set(handles.inSpectrumHandle,'ydata',inputSpecData-maxInputSpec+maxEnvelope); end; end; end; set(handles.harmonicsHandle,'xdata', ... handles.harmonicAxis*handles.F0*handles.vtLength/handles.vtLengthReference); guidata(handles.vtTester, handles); %axes(handles.VT3d) %axis([0 1 [-1 1 -1 1]/max(crossSection)]); %axes(handles.gainPlot); end function lsfVector = handleToLsf(handles) fs = handles.samplingFrequency; areaFunction = exp(handles.logArea); ref = Zarea2ref(areaFunction); alp = Zk2alp(ref); lsfVector = poly2lsf(alp)/2/pi*fs; end function [gaindB,fx] = handleToGain(handles) fs = handles.samplingFrequency; areaFunction = exp(handles.logArea); ref = Zarea2ref(areaFunction); alp = Zk2alp(ref); fftl = 8192*2;%32768; make this compatible with LF designer x = zeros(fftl,1); x(1) = 1; y = filter(1,alp,x); gaindB = 20*log10(abs(fft(y))); gaindB = gaindB-gaindB(1); fx = (0:fftl-1)/fftl*fs; end function rootVector = handleToRoots(handles) fs = handles.samplingFrequency; areaFunction = exp(handles.logArea); ref = Zarea2ref(areaFunction); alp = Zk2alp(ref); r = roots(alp); poleFrequencies = angle(r)/pi*fs/2; poleBandWidths = -log(abs(r))/pi*fs; rootVector = [poleFrequencies poleBandWidths]; end function soundItBody(handles) fs = handles.samplingFrequency; areaFunction = exp(handles.logArea); ref = Zarea2ref(areaFunction); alp = Zk2alp(ref); sourceSignalStr = generateSource(handles); handles = sourceSignalStr.handles; x = sourceSignalStr.signal; y = filter(1,alp,x); y = y/max(abs(y))*0.9; if handles.vtLength == handles.vtLengthReference handles.player1 = audioplayer(y,fs); vtl = handles.vtLength; else vtl = handles.vtLength; tx = (0:length(y)-1)'/fs; y = interp1(tx*vtl/handles.vtLengthReference,y,... (0:1/fs:tx(end)*vtl/handles.vtLengthReference)','linear','extrap'); handles.player1 = audioplayer(y,fs); end; if isfield(handles,'F0') %disp('F0 exist') f0Base = handles.F0; else f0Base = 125; end windowLengthInms = 60; handles.windowShiftInms = 50; windowType = 'nuttallwin12'; handles.sgramStr = stftSpectrogramStructure(y,fs,windowLengthInms,handles.windowShiftInms,windowType); sgramFaxis = handles.sgramStr.frequencyAxis; transferFunction = get(handles.gainPlotHandle,'ydata'); fAxis = get(handles.gainPlotHandle,'xdata'); f0Index = round(f0Base/fAxis(2)*vtl/handles.vtLengthReference); handles.currentTransferFunction = transferFunction; handles.fAxisForTrandferFunction = fAxis; handles.outSignalScanIndex = round(f0Base/sgramFaxis(2)+(-4:4)); handles.levelAtF0 = transferFunction(f0Index); set(handles.player1,'TimerFcn',{@outSpectrumDisplayFcn,handles},'TimerPeriod',0.10); handles.playInterruptionCount = 0; handles.maxInterruptionCount = floor(length(y)/fs/(handles.windowShiftInms/1000)-1); guidata(handles.vtTester,handles); stop(handles.timer); playblocking(handles.player1); set(handles.outSpectrumHandle,'visible','off'); start(handles.timer); handles.synthesizedSound = y; set(handles.SaveButton,'enable','on'); guidata(handles.vtTester,handles); end function outSpectrumDisplayFcn(src,evnt,handles) handles = guidata(handles.vtTester); handles.playInterruptionCount = handles.playInterruptionCount+1; if handles.playInterruptionCount <= handles.maxInterruptionCount tmpSpectrumSlice = handles.sgramStr.dBspectrogram(:,handles.playInterruptionCount); tmplevelAtF0 = max(tmpSpectrumSlice(handles.outSignalScanIndex)); tmpSpectrumSlice = tmpSpectrumSlice-tmplevelAtF0+handles.levelAtF0; set(handles.outSpectrumHandle,'visible','on', ... 'ydata',tmpSpectrumSlice, ... 'xdata',handles.sgramStr.frequencyAxis*handles.vtLength/handles.vtLengthReference); % sourceSpectrumSlice = handles.sourceSgram(:,handles.playInterruptionCount); % resampledSlice = interp1(handles.sourceFx(:,handles.playInterruptionCount),sourceSpectrumSlice, ... % handles.fAxisForTrandferFunction*handles.vtLength/handles.vtLengthReference,'linear','extrap'); % resampledTransferFunctionSlice = interp1(handles.fAxisForTrandferFunction*handles,handles.currentTransferFunction, ... % handles.fAxisForTrandferFunction*handles.vtLength/handles.vtLengthReference,'linear','extrap'); %handles.sourceSgram = sourceSgram; %handles.sourceFx = sourceFx; % set(handles.totalEnvelopeHandle,'visible','on','ydata',resampledTransferFunctionSlice(:)+resampledSlice(:), ... % 'xdata',handles.fAxisForTrandferFunction*handles.vtLength/handles.vtLengthReference); end; guidata(handles.vtTester,handles); end function sourceSignalStr = generateSource(handles) vtl = handles.vtLength; fs = handles.samplingFrequency/vtl*handles.vtLengthReference; duration = handles.duration; tt = (0:1/fs:duration)'; pWidth = 0.003; % pulse width 3 ms tHalf = tt(tt<pWidth); pSingle = sin(pi*(tHalf/pWidth).^2); if isfield(handles,'F0') %disp('F0 exist') f0Base = handles.F0; else f0Base = 125; end vibratoDepth = handles.vibratoDepth; %0.25; vibratoFrequency = handles.vibratoFrequency; %5.5; switch handles.currentVQName case 'Design' if isempty(handles.LFDesigner) handles.LFDesigner = lfModelDesignerX(handles.vtTester); guidata(handles.vtTester,handles); end; if ~ishghandle(handles.LFDesigner) handles.LFDesigner = lfModelDesignerX(handles.vtTester); guidata(handles.vtTester,handles); end; lfDesignerGUIdata = guidata(handles.LFDesigner); LFparameters = lfDesignerGUIdata.LFparameters; otherwise LFparameters = handles.LFparameters; end; switch handles.variableF0 case 'off' f0 = 2.0.^((log2(f0Base)*12+0.005*vibratoDepth*sin(2*pi*vibratoFrequency*tt))/12); outStr = AAFLFmodelFromF0Trajectory(f0,tt,fs,LFparameters.tp,LFparameters.te,LFparameters.ta,LFparameters.tc); case 'on' if isempty(handles.LFDesigner) handles.LFDesigner = lfModelDesignerX(handles.vtTester); guidata(handles.vtTester,handles); end; if ~ishghandle(handles.LFDesigner) handles.LFDesigner = lfModelDesignerX(handles.vtTester); guidata(handles.vtTester,handles); end; %vtShapeToSoundTestV24('SoundItButton_Callback',handles.parentUserData.SoundItButton,[], ... % handles.parentUserData); lfModelHandles = guidata(handles.LFDesigner); lfModelDesignerX('generateSource_Callback',handles.vtTester,[],lfModelHandles); handles = guidata(handles.vtTester); outStr = handles.outStr; f0 = handles.generatedF0; tt = handles.generatedTime; f0Base = handles.f0Base; end; x = outStr.antiAliasedSignal; sourceSignalStr.signal = fftfilt(handles.equalizerStr.minimumPhaseResponseW,x); %sourceSignalStr.handles = handles; %a = 1; %if 1 == 2; Tw = 2/(fs/2); Tworg = Tw*f0Base; timeAxis = ((round(-0.2*fs/f0Base):round(1.2*fs/f0Base))'/fs)/(1/f0Base); fftlTmp = 8192*2; fxTmp = (0:fftlTmp-1)'/fftlTmp*fs; modelOut = sourceByLFmodelAAF(timeAxis,LFparameters.tp,LFparameters.te,LFparameters.ta,LFparameters.tc,Tworg); %if 1 == 2 sgramTemporalPositions = 0:0.10:length(x)/fs; f0Sgram = interp1(tt,f0,sgramTemporalPositions,'linear','extrap'); sourceSgram = zeros(fftlTmp/2+1,length(f0Sgram)); sourceFx = sourceSgram; for ii = 1:length(sgramTemporalPositions) rawPw = 20*log10(abs(fft(modelOut.antiAliasedSource,fftlTmp))); iidx = round(f0Sgram(ii)/fxTmp(2))+1; rawPw = rawPw-rawPw(iidx); sourceSgram(:,ii) = rawPw(1:fftlTmp/2+1); sourceFx(:,ii) = fxTmp(1:fftlTmp/2+1)*f0Sgram(ii)/f0Base; end; handles.sourceSgram = sourceSgram; handles.sourceFx = sourceFx; if 1 == 2 vtSpectrumEnvelope = get(handles.gainPlotHandle,'ydata'); vtSpectrumEnvelope = vtSpectrumEnvelope(1:fftlTmp/2+1); vtSpectrumEnvelope(sourceFx(:,1)<f0Sgram(1)) = NaN; set(handles.totalEnvelopeHandle,'visible','on','ydata',vtSpectrumEnvelope(:)+sourceSgram(:,1), ... 'xdata',sourceFx(:,1)); end; sourceSignalStr.handles = handles; %end; if 1 == 2 fundamentalComponent = sin(cumsum(2*pi*f0/fs)); signOfFcomp = sign(fundamentalComponent); signOfFcompPre = signOfFcomp([1;(1:length(signOfFcomp)-1)']); eventLocation = tt(signOfFcomp > signOfFcompPre); %eventLocation = (0:1/f0:tt(end))'; tmpIndex = (1:length(pSingle))'; eventLocationIndex = round(eventLocation*fs); sourceSignal = tt*0; for ii = 1:length(eventLocationIndex) sourceSignal(max(1,min(length(sourceSignal),tmpIndex+eventLocationIndex(ii)))) = pSingle; end; end; end %---- basic LPC functions function k = Zarea2ref(s) % Area to reflection coefficients % s : cross sectional area % k : reflection coefficients n = length(s)-1; k = zeros(n,1); for ii=1:n k(ii) = (s(ii+1)-s(ii))/(s(ii+1)+s(ii)); end; end function alp = Zk2alp(k) % Reflection coefficients to predictor % k : reflection coefficient % alp : predictor % by Hideki Kawahara n = length(k); a = zeros(n,1); b = zeros(n,1); a(1) = k(1); for ii=2:n for jj = 1:ii-1 b(jj) = a(jj)-k(ii)*a(ii-jj); end; a = b; a(ii) = k(ii); end; alp = [1;-a]; end % --- Executes on button press in releaseToPlayEnableRadioButton. function releaseToPlayEnableRadioButton_Callback(hObject, eventdata, handles) % hObject handle to releaseToPlayEnableRadioButton (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 releaseToPlayEnableRadioButton handles.releaseToPlay = get(hObject,'Value'); guidata(handles.vtTester, handles); end % --- 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) [file,path] = uigetfile({'*.mat';'*.txt'},'Select saved .mat file or compliant .txt file'); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 disp('Load is cancelled!'); return; end; end; switch file(end-2:end) case 'mat' handles = loadSavedMatFile(handles,path,file); case 'txt' handles = loadCompliantTextFile(handles,path,file); end; syncVTL(handles.vtLength,handles) set(handles.poleMarker,'visible','off'); set(handles.bandWidthValue,'visible','off'); set(handles.frequencyValue,'visible','off'); set(handles.bandWidthTitleText,'visible','off'); set(handles.frequencyTitleText,'visible','off'); guidata(handles.vtTester, handles); updatePlots(handles) end function handles = loadCompliantTextFile(handles,path,file) fid = fopen([path file]); tline = fgetl(fid); readItem = textscan(tline,'%s %s %s %f'); if strcmp('Number',readItem{1}) && strcmp('of',readItem{2}) nSection = readItem{4}; else fclose(fid);disp('Number of section is missing.');return; end; tline = fgetl(fid); readItem = textscan(tline,'%s %s %s %f'); if strcmp('Vocal',readItem{1}) && strcmp('tract',readItem{2}) handles.vtLength = readItem{4}; if abs(handles.vtLength-handles.vtLengthReference) < 0.01 handles.vtLength = handles.vtLengthReference; end; else fclose(fid);disp('Vocal tract length is missing.');return; end; tline = fgetl(fid); readItem = textscan(tline,'%s %s %s %f'); if strcmp('List',readItem{1}) && strcmp('of',readItem{2}) handles.vtLength = handles.vtLength; % do nothing else fclose(fid);disp('Data prefix is missing.');return; end; xData = (0:nSection-1)'/(nSection-1)*handles.vtLength; tmpArea = zeros(nSection,1); for ii = 1:nSection tline = fgetl(fid); if ischar(tline) tmp = textscan(tline,'%f'); tmpArea(ii) = tmp{1}; else fclose(fid);disp('Data is missing.');return; end; end; %tmpArea %handles.nSection;% logArea = interp1(xData,log(tmpArea),(0:handles.nSection-1)'/(handles.nSection-1)*xData(end),'linear','extrap'); handles.logArea(1:handles.nSection) = logArea; %handles.logArea fclose(fid); end function handles = loadSavedMatFile(handles,path,file) tmp = load([path file]); xData = get(handles.logAreaPlotHandle,'xData'); if ~isfield(tmp,'outStructure') disp([path file ' does not consist of relevant data!']);return; end; if ~isfield(tmp.outStructure,'finalAreaFunction') disp([path file ' does not consist of relevant data!']);return; end; if tmp.outStructure.finalAreaFunction(end) ~= 1 || ... length(tmp.outStructure.finalAreaFunction) ~= length(xData) if length(tmp.outStructure.finalAreaFunction) ~= 46 disp([path file ' does not consist of relevant data!']);return; else disp([path file ' is in old format. Updating']); deltaX = tmp.outStructure.finalLocationData(2)-tmp.outStructure.finalLocationData(1); vtLength = deltaX*(length(tmp.outStructure.finalAreaFunction)-1); recordedXdata = (0:44)/44*vtLength; tmpxData = (0:length(xData)-2)/(length(xData)-2)*vtLength; logArea = interp1(recordedXdata,log(tmp.outStructure.finalAreaFunction(1:end-1)), ... [tmpxData tmpxData(end)],'linear','extrap'); logArea(end) = 0; handles.logArea = logArea; end; else logArea = log(tmp.outStructure.finalAreaFunction); handles.logArea = log(tmp.outStructure.finalAreaFunction); end; set(handles.logAreaPlotHandle,'ydata',logArea); if isfield(tmp.outStructure,'vtLength') vtl = tmp.outStructure.vtLength; else vtl = handles.vtLengthReference; end; handles.vtLength = vtl; end % --- 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) outFileNameRoot = ['vts' datestr(now,30)]; vtTestGUIStructure = guidata(handles.vtTester); vtl = handles.vtLength; outStructure = struct; outStructure.vtLength = vtl; outStructure.finalLocationData = get(handles.logAreaPlotHandle,'xdata')/handles.vtLengthReference*vtl; outStructure.finalLogAreaData = get(handles.logAreaPlotHandle,'ydata'); outStructure.finalAreaFunction = exp(outStructure.finalLogAreaData); outStructure.LFparameters = handles.LFparameters; outStructure.synthesizedSound = vtTestGUIStructure.synthesizedSound; outStructure.samplingFrequency = vtTestGUIStructure.samplingFrequency; outStructure.lastUpdata = datestr(now); switch get(handles.inSpectrumHandle,'visible') case 'on' outStructure.inputSegment = handles.inputSegment; end; [file,path] = uiputfile('*','Save status (.mat), area function (.txt) and sound at once.',outFileNameRoot); if length(file) == 1 && length(path) == 1 if file == 0 || path == 0 disp('Save is cancelled!'); return; end; end; x = outStructure.finalLocationData; y = exp(outStructure.finalLogAreaData); save([path [file '.mat']],'outStructure'); audiowrite([path [file '.wav']],handles.synthesizedSound,handles.samplingFrequency); fid = fopen([path [file '.txt']],'w'); nSection = length(x)-1; fprintf(fid,'Number of sections: %4d\n',nSection); fprintf(fid,'Vocal tract length: %7.4f\n',vtl); fprintf(fid,'List of relative area from lip to glottis\n'); for ii = 1:nSection %fprintf(fid,'%5.2f %8.2f\n',x(ii),y(ii)); fprintf(fid,'%8.2f\n',y(ii)); end; fclose(fid); end % --- Executes on button press in modifierResetPushbutton. function modifierResetPushbutton_Callback(hObject, eventdata, handles) % hObject handle to modifierResetPushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.magnifierKnob,'ydata',0); handles.magnifierValue = 0; handles.coefficientList = handles.coefficientList*0; ydata = get(handles.modifierHandle,'ydata'); set(handles.modifierIndicatorHandle,'ydata',ydata*handles.magnifierValue+log(16)); yData = handles.modifierBasis*handles.coefficientList(:); for ii = 1:length(handles.coefficientList) set(handles.modifierComponentHandle(ii),'ydata',handles.modifierBasis(:,ii)*handles.coefficientList(ii)); set(handles.modifierAnchorHandles(ii),'ydata',handles.coefficientList(ii)); end; set(handles.modifierHandle,'yData',yData); handles.logAreaDeviation = handles.logArea; updatePlots(handles) guidata(handles.vtTester,handles); end function frequencyValue_Callback(hObject, eventdata, handles) % hObject handle to frequencyValue (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 frequencyValue as text % str2double(get(hObject,'String')) returns contents of frequencyValue as a double frequencyString = get(handles.frequencyValue,'string');%currentPoint(1,1); frequencyTmp = str2double(frequencyString); frequency = frequencyTmp*handles.vtLength/handles.vtLengthReference; if ~isnan(frequency) frequency = max(1,min(5000,frequency)); else frequency = handles.lastFrequency; end bandWidthString = get(handles.bandWidthValue,'string');%10.0.^(-currentPoint(1,2)); bandWidthTmp = str2double(bandWidthString); bandWidth = bandWidthTmp*handles.vtLength/handles.vtLengthReference; if ~isnan(bandWidth) bandWidth = max(2,min(1000,bandWidth)); else bandWidth = handles.lastBandWidth; end handles = updateParametersFromRoots(handles,frequency,bandWidth); %----- log area plot logAreaPlot(handles); %------ crossSection = exp(handles.logArea); crossSection = crossSection/max(crossSection); [X,Y,Z] = cylinder(crossSection,40); set(handles.tract3D,'xdata',Z,'ydata',Y,'zdata',X); guidata(handles.vtTester,handles); if handles.releaseToPlay soundItBody(handles) end; end % --- Executes during object creation, after setting all properties. function frequencyValue_CreateFcn(hObject, eventdata, handles) % hObject handle to frequencyValue (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 end function bandWidthValue_Callback(hObject, eventdata, handles) % hObject handle to bandWidthValue (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 bandWidthValue as text % str2double(get(hObject,'String')) returns contents of bandWidthValue as a double frequencyString = get(handles.frequencyValue,'string');%currentPoint(1,1); frequencyTmp = str2double(frequencyString); frequency = frequencyTmp*handles.vtLength/handles.vtLengthReference; if ~isnan(frequency) frequency = max(1,min(5000,frequency)); else frequency = handles.lastFrequency; end bandWidthString = get(handles.bandWidthValue,'string');%10.0.^(-currentPoint(1,2)); bandWidthTmp = str2double(bandWidthString); bandWidth = bandWidthTmp*handles.vtLength/handles.vtLengthReference; if ~isnan(bandWidth) bandWidth = max(2,min(1000,bandWidth)); else bandWidth = handles.lastBandWidth; end handles = updateParametersFromRoots(handles,frequency,bandWidth); %----- log area plot logAreaPlot(handles); %------ crossSection = exp(handles.logArea); crossSection = crossSection/max(crossSection); [X,Y,Z] = cylinder(crossSection,40); set(handles.tract3D,'xdata',Z,'ydata',Y,'zdata',X); guidata(handles.vtTester,handles); if handles.releaseToPlay soundItBody(handles) end; end % --- Executes during object creation, after setting all properties. function bandWidthValue_CreateFcn(hObject, eventdata, handles) % hObject handle to bandWidthValue (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 end %---- private function for defining pointer function handles = defineLRPointerShape(handles) tmp = imread('lrTool.png'); [nRow,nColumn] = size(tmp); pointerShapeCData = double(tmp)+NaN; for ii = 1:nColumn for jj = 1:nRow if tmp(jj,ii) > 200;pointerShapeCData(jj,ii) = 2;end; if tmp(jj,ii) < 100;pointerShapeCData(jj,ii) = 1;end; end; end; handles.pointerShapeCDataForLR = pointerShapeCData; handles.hotSpotForLR = [7,nRow/2]; end function handles = definePenPointerShape(handles) tmp = imread('penTool.png'); tmpV = double(tmp>0); [nRow,nColumn] = size(tmpV); pointerShapeCData = tmpV+NaN; for ii = 1:nColumn lowerIndex = min(find(tmpV(:,ii)==0)); upperIndex = max(find(tmpV(:,ii)==0)); for jj = max(1,lowerIndex-1):min(nRow,upperIndex+1) pointerShapeCData(jj,ii) = tmpV(jj,ii)+1; end; end; handles.pointerShapeCDataForPen = pointerShapeCData; handles.hotSpotForPen = [nRow,1]; end %---- private function for defining pointer function handles = definePickerPointerShape(handles) tmp = imread('pickTool.png'); [nRow,nColumn] = size(tmp); pointerShapeCData = double(tmp)+NaN; for ii = 1:nColumn for jj = 1:nRow if tmp(jj,ii) > 200;pointerShapeCData(jj,ii) = 2;end; if tmp(jj,ii) < 100;pointerShapeCData(jj,ii) = 1;end; end; end; handles.pointerShapeCDataForPicker = pointerShapeCData; handles.hotSpotForPicker = [7,7]; end function insideInd = isInsideAxis(axisHandle) insideInd = false; currentPoint = get(axisHandle,'currentPoint'); %currentPoint xLimit = get(axisHandle,'xlim'); yLimit = get(axisHandle,'ylim'); if ((currentPoint(1,1)-xLimit(1))*(currentPoint(1,1)-xLimit(2)) < 0) && ... ((currentPoint(1,2)-yLimit(1))*(currentPoint(1,2)-yLimit(2)) < 0) insideInd = true; end; end % --- Executes on button press in shawallButton. function shawallButton_Callback(hObject, eventdata, handles) % hObject handle to shawallButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.coefficientList = handles.coefficientList*0+1; yData = handles.modifierBasis*handles.coefficientList(:); for ii = 1:length(handles.coefficientList) set(handles.modifierComponentHandle(ii),'ydata',handles.modifierBasis(:,ii)*handles.coefficientList(ii)); set(handles.modifierAnchorHandles(ii),'ydata',handles.coefficientList(ii)); end; if max(abs(yData)) > 1;yData = yData/max(abs(yData));end; set(handles.modifierHandle,'yData',yData); ydata = get(handles.modifierHandle,'ydata'); set(handles.modifierIndicatorHandle,'ydata',ydata*handles.magnifierValue+log(16)); guidata(handles.vtTester,handles); end function vtlEdit_Callback(hObject, eventdata, handles) % hObject handle to vtlEdit (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 vtlEdit as text % str2double(get(hObject,'String')) returns contents of vtlEdit as a double vtl = str2double(get(hObject,'String')); if ~isnan(vtl) && vtl > 10 && vtl < 35 vtl = vtl; else vtl = handles.vtLengthReference; end; handles.vtLength = vtl; syncVTL(vtl,handles); %handles guidata(handles.vtTester,handles); end % --- Executes during object creation, after setting all properties. function vtlEdit_CreateFcn(hObject, eventdata, handles) % hObject handle to vtlEdit (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 end % --- Executes on button press in resetVTLbutton. function resetVTLbutton_Callback(hObject, eventdata, handles) % hObject handle to resetVTLbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.vtLength = handles.vtLengthReference; syncVTL(handles.vtLengthReference,handles); set(handles.vtlHandle,'xdata',8*[1 1]); set(handles.totalEnvelopeHandle,'linewidth',1); guidata(handles.vtTester,handles); if handles.releaseToPlay soundItBody(handles) end; end %----- private function for VTL synchronization function syncVTL(vtl,handles) vtl = abs(vtl); set(handles.vtlEdit,'string',num2str(vtl,'%4.2f')); set(handles.vtlHandle,'xdata',8*handles.vtLengthReference/vtl*[1 1]); set(handles.VTDrawer,'xtick',handles.vtDrawerXtick*handles.vtLengthReference/vtl); set(handles.gainPlot,'xtick',[1000:1000:10000]*vtl/handles.vtLengthReference); set(handles.gainRootAxis(2),'ytick',-log10(vtl/handles.vtLengthReference*[2000 1000 700 500 300 200 100 70 50 30 20 10 7 5 3 2 1])); envelopeSpec = get(handles.totalEnvelopeHandle,'ydata'); envelopeFaxis = get(handles.totalEnvelopeHandle,'xdata'); maxEnvelope = max(envelopeSpec(envelopeFaxis<5000)); set(handles.harmonicsHandle,'xdata', ... handles.harmonicAxis*handles.F0*vtl/handles.vtLengthReference); switch get(handles.inSpectrumHandle,'visible'); case 'on' %ylim = get(handles.gainRootAxis(1),'ylim'); set(handles.inSpectrumHandle,'xdata',handles.nominalFaxis/handles.vtLengthReference*vtl); inputSpecData = get(handles.inSpectrumHandle,'ydata'); inputSpecFAxis = get(handles.inSpectrumHandle,'xdata'); maxInputSpec = max(inputSpecData(inputSpecFAxis<5000)); set(handles.inSpectrumHandle,'ydata',inputSpecData-maxInputSpec+maxEnvelope); end; for ii = 1:length(handles.vtDrawerXGridHandleList) set(handles.vtDrawerXGridHandleList(ii),'xdata',ii*handles.vtLengthReference/vtl*[1 1]); end; for ii = 1:length(handles.modifierMinorGridList) set(handles.modifierMinorGridList(ii),'xdata',handles.minorGrid(ii)*handles.vtLengthReference/vtl*[1 1]); end; for ii = 1:length(handles.modifierMajorGridList) set(handles.modifierMajorGridList(ii),'xdata',handles.majorGrid(ii)*handles.vtLengthReference/vtl*[1 1]); end; if ~isempty(handles.LFDesigner) && ishghandle(handles.LFDesigner) lfDesignerGUIdata = guidata(handles.LFDesigner); if isfield(handles,'F0') %disp('F0 exist') f0Base = handles.F0; else f0Base = 125; end modelFaxis = get(handles.gainPlotHandle,'xdata')*handles.vtLengthReference/vtl; modelVTgain = get(handles.gainPlotHandle,'ydata'); if isfield(lfDesignerGUIdata,'LFmodelGenericSpectrum') sourceSpectrum = lfDesignerGUIdata.LFmodelGenericSpectrum; levelAtF0 = interp1(lfDesignerGUIdata.LFmodelGenericFaxis,sourceSpectrum,1); sourceGain = interp1(lfDesignerGUIdata.LFmodelGenericFaxis*f0Base,sourceSpectrum-levelAtF0,modelFaxis*handles.vtLengthReference/vtl,'linear','extrap'); scaledVTgain = interp1(modelFaxis/handles.vtLengthReference*vtl,modelVTgain,modelFaxis,'linear','extrap'); set(handles.totalEnvelopeHandle,'visible','on',... 'xdata',modelFaxis,'ydata',scaledVTgain(:)+sourceGain(:),'linewidth',3); end; end; end function F0Edit_Callback(hObject, eventdata, handles) % hObject handle to F0Edit (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 F0Edit as text % str2double(get(hObject,'String')) returns contents of F0Edit as a double tmpF0 = str2double(get(hObject,'String')); if ~isnan(tmpF0) handles.F0 = max(55,min(880,tmpF0)); end; guidata(handles.vtTester,handles); synchSource(handles) end % --- Executes during object creation, after setting all properties. function F0Edit_CreateFcn(hObject, eventdata, handles) % hObject handle to F0Edit (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 end % --- Executes on selection change in noteNamePopup. function noteNamePopup_Callback(hObject, eventdata, handles) % hObject handle to noteNamePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns noteNamePopup contents as cell array % contents{get(hObject,'Value')} returns selected item from noteNamePopup itemID = get(hObject,'Value'); switch itemID case 1 handles.F0 = 125; handles = closeLFdesigner(handles,'on'); handles.variableF0 = 'off'; case 2 handles.F0 = 250; handles = closeLFdesigner(handles,'on'); handles.variableF0 = 'off'; case 3 handles = closeLFdesigner(handles,'off'); handles.variableF0 = 'on'; guidata(handles.vtTester,handles); if isempty(handles.LFDesigner) handles.LFDesigner = lfModelDesignerX(handles.vtTester); end; if ishghandle(handles.LFDesigner) lfDesignerGUIdata = guidata(handles.LFDesigner); handles.LFparameters = lfDesignerGUIdata.LFparameters; handles.currentVQName = 'Design'; set(handles.voiceQualityPopup,'value',4); set(handles.harmonicsHandle,'visible','on'); guidata(handles.vtTester,handles); if handles.releaseToPlay soundItBody(handles) end; else handles = defaultLFparameters(handles); guidata(handles.vtTester,handles); end; otherwise handles.F0 = 55*2.0.^((itemID-4)/12); handles = closeLFdesigner(handles,'on'); handles.variableF0 = 'off'; end; guidata(handles.vtTester,handles); synchSource(handles) end function handles = closeLFdesigner(handles,variableF0State) % variableF0State: on or off if ~isempty(handles.LFDesigner) && strcmp(handles.variableF0,variableF0State) if ishghandle(handles.LFDesigner) lfDesignerUserData = guidata(handles.LFDesigner); %eval([fName '(instruction,handles.parentUserData.SoundItButton,[],handles.parentUserData);']); %quitButton_Callback(hObject, eventdata, handles) lfModelDesignerX('quitButton_Callback',lfDesignerUserData.quitButton,[],lfDesignerUserData); set(handles.harmonicsHandle,'visible','off'); handles.LFDesigner = []; end; end; end % --- Executes during object creation, after setting all properties. function noteNamePopup_CreateFcn(hObject, eventdata, handles) % hObject handle to noteNamePopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end function synchSource(handles) set(handles.F0Edit,'string',num2str(handles.F0,'%5.1f')); set(handles.vibratoRateEdit,'string',num2str(handles.vibratoFrequency,'%5.2f')); set(handles.vibratoDepthEdit,'string',num2str(handles.vibratoDepth,'%5.0f')); noteIndex = round(log2(handles.F0/55)*12+4); if handles.F0 == 125 && ~(get(handles.noteNamePopup,'value') == 3) set(handles.noteNamePopup,'value',1); elseif handles.F0 == 250 && ~(get(handles.noteNamePopup,'value') == 3) set(handles.noteNamePopup,'value',2); elseif strcmp(handles.variableF0,'on') set(handles.noteNamePopup,'value',3); else set(handles.noteNamePopup,'value',noteIndex); end; %guidata(handles.vtTester,handles); updatePlots(handles); if handles.releaseToPlay soundItBody(handles) end; end % --- Executes on selection change in voiceQualityPopup. function voiceQualityPopup_Callback(hObject, eventdata, handles) % hObject handle to voiceQualityPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns voiceQualityPopup contents as cell array % contents{get(hObject,'Value')} returns selected item from voiceQualityPopup itemID = get(hObject,'Value'); LFparameters = handles.LFparameters; switch itemID case {1,2,3} handles = closeLFdesigner(handles,'off'); %if ~isempty(handles.LFDesigner) % if ishghandle(handles.LFDesigner) % close(handles.LFDesigner); % end; % handles.LFDesigner = []; %end; LFparameterVector = handles.LFparametersBaseSet(itemID,:); LFparameters.tp = LFparameterVector(1); LFparameters.te = LFparameterVector(2); LFparameters.ta = LFparameterVector(3); LFparameters.tc = LFparameterVector(4); handles.LFparameters = LFparameters; handles.currentVQName = char(handles.LFparameterNames{itemID}); guidata(handles.vtTester,handles); if handles.releaseToPlay soundItBody(handles) end; case 4 if isempty(handles.LFDesigner) handles.LFDesigner = lfModelDesignerX(handles.vtTester); end; if ishghandle(handles.LFDesigner) lfDesignerGUIdata = guidata(handles.LFDesigner); handles.LFparameters = lfDesignerGUIdata.LFparameters; handles.currentVQName = 'Design'; set(handles.harmonicsHandle,'visible','on'); guidata(handles.vtTester,handles); if handles.releaseToPlay soundItBody(handles) end; else handles = defaultLFparameters(handles); guidata(handles.vtTester,handles); end; end; updatePlots(handles); end % --- Executes during object creation, after setting all properties. function voiceQualityPopup_CreateFcn(hObject, eventdata, handles) % hObject handle to voiceQualityPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end function vibratoRateEdit_Callback(hObject, eventdata, handles) % hObject handle to vibratoRateEdit (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 vibratoRateEdit as text % str2double(get(hObject,'String')) returns contents of vibratoRateEdit as a double tmpFrequency = str2double(get(hObject,'String')); if ~isnan(tmpFrequency) handles.vibratoFrequency = tmpFrequency; guidata(handles.vtTester,handles); synchSource(handles); end; end % --- Executes during object creation, after setting all properties. function vibratoRateEdit_CreateFcn(hObject, eventdata, handles) % hObject handle to vibratoRateEdit (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 end function vibratoDepthEdit_Callback(hObject, eventdata, handles) % hObject handle to vibratoDepthEdit (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 vibratoDepthEdit as text % str2double(get(hObject,'String')) returns contents of vibratoDepthEdit as a double tmpDepth = str2double(get(hObject,'String')); if ~isnan(tmpDepth) handles.vibratoDepth = tmpDepth; guidata(handles.vtTester,handles); synchSource(handles); end; end % --- Executes during object creation, after setting all properties. function vibratoDepthEdit_CreateFcn(hObject, eventdata, handles) % hObject handle to vibratoDepthEdit (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 end % --- Executes on selection change in durationPopup. function durationPopup_Callback(hObject, eventdata, handles) % hObject handle to durationPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns durationPopup contents as cell array % contents{get(hObject,'Value')} returns selected item from durationPopup itemID = get(hObject,'Value'); handles.duration = handles.durationList(itemID); guidata(handles.vtTester,handles); synchSource(handles) end % --- Executes during object creation, after setting all properties. function durationPopup_CreateFcn(hObject, eventdata, handles) % hObject handle to durationPopup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end % --- Executes on button press in sourceResetButton. function sourceResetButton_Callback(hObject, eventdata, handles) % hObject handle to sourceResetButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.F0 = 125; handles.duration = 1; set(handles.durationPopup,'value',3); set(handles.noteNamePopup,'value',1); handles.vibratoDepth = 50; handles.vibratoFrequency = 5.5; handles = closeLFdesigner(handles,'on'); handles = closeLFdesigner(handles,'off'); guidata(handles.vtTester,handles); synchSource(handles) end % --- Executes on button press in startMonitorButton. function startMonitorButton_Callback(hObject, eventdata, handles) % hObject handle to startMonitorButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.audioCounterText,'visible','on','string',num2str(handles.audioRecordCount)); handles.audioRecordCount = handles.maximumRecordCount; record(handles.audioRecorder); set(handles.stopMonitorButton,'enable','on'); set(handles.startMonitorButton,'enable','off'); set(handles.audioCounterText,'visible','on','string',num2str(handles.audioRecordCount)); guidata(handles.vtTester,handles); end % --- Executes on button press in stopMonitorButton. function stopMonitorButton_Callback(hObject, eventdata, handles) % hObject handle to stopMonitorButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) stop(handles.audioRecorder); set(handles.stopMonitorButton,'enable','off'); set(handles.startMonitorButton,'enable','on'); end % --- Executes on button press in monitorRadioButton. function monitorRadioButton_Callback(hObject, eventdata, handles) % hObject handle to monitorRadioButton (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 monitorRadioButton switch get(hObject,'Value') case 1 set(handles.SoundMonitorPanel,'visible','on'); set(handles.stopMonitorButton,'visible','on'); set(handles.stopMonitorButton,'enable','off'); set(handles.startMonitorButton,'visible','on'); set(handles.startMonitorButton,'enable','on'); set(handles.inSpectrumHandle,'visible','on'); set(handles.playMonitorButton,'visible','on'); if length(handles.monitoredSound) < 100; set(handles.playMonitorButton,'enable','off');end; case 0 stop(handles.audioRecorder); set(handles.SoundMonitorPanel,'visible','off'); set(handles.stopMonitorButton,'visible','off'); set(handles.startMonitorButton,'visible','off'); set(handles.inSpectrumHandle,'visible','off'); set(handles.audioCounterText,'visible','off'); set(handles.playMonitorButton,'visible','on'); end; guidata(handles.vtTester,handles); end function spectrumMonitor(src,evnt,handles) handles = guidata(handles.vtTester); handles.audioRecordCount = handles.audioRecordCount-1; set(handles.audioCounterText,'string',num2str(handles.audioRecordCount)); %if 1 == 2 fftl = 8192; fs = handles.samplingFrequency; w = nuttallwin12(round(0.06*fs)); fx = (0:fftl-1)/fftl*fs/handles.vtLengthReference*handles.vtLength;% handles.vtLengthReference handles.vtLength handles.nominalFaxis = (0:fftl-1)/fftl*fs; ylim = get(handles.gainRootAxis(1),'ylim'); y = getaudiodata(handles.audioRecorder); y = y(:); if length(y)>length(w) power = 20*log10(abs(fft(w.*y(end-length(w):end-1),fftl))); maxPower = max(power(fx<5000)); scaledPower = power-maxPower+ylim(2)-5; set(handles.inSpectrumHandle,'xdata',fx,'ydata',scaledPower); handles.inputSegment = y(end-length(w):end-1); handles.monitoredSound = y(end-min(length(y),round(0.2*fs))+1:end); set(handles.playMonitorButton,'enable','on'); end; if handles.audioRecordCount < 0 switch get(handles.timer,'running') case 'on' stop(handles.timer); end stop(handles.audioRecorder); handles.audioRecordCount = handles.maximumRecordCount; set(handles.playMonitorButton,'enable','off'); record(handles.audioRecorder); switch get(handles.timer,'running') case 'off' start(handles.timer); end end; switch get(handles.monitorRadioButton,'value') case 'off' stop(handles.audioRecorder); end; %end; guidata(handles.vtTester,handles); end % --- Executes on button press in playMonitorButton. function playMonitorButton_Callback(hObject, eventdata, handles) % hObject handle to playMonitorButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) monitorSound = handles.monitoredSound; handles.audioPlayer = audioplayer(monitorSound/max(abs(monitorSound))*0.99,handles.samplingFrequency); playblocking(handles.audioPlayer); end
github
HidekiKawahara/SparkNG-master
desa2.m
.m
SparkNG-master/src/desa2.m
352
utf_8
645b8fdf5631bf95c13092c833d1a575
function output = desa2(x, fs) phx = tkeo(x); phy = tkeo(x([2:end, end]) - x([1, 1:end-1])); omg = asin(real(sqrt(phy ./ phx / 4))); amp = 2 * phx ./ real(sqrt(phy)); output.omg = omg([3, 3, 3:end-2, end-2, end-2]) * fs; output.amp = amp([3, 3, 3:end-2, end-2, end-2]); end function phi = tkeo(x) phi = x .^ 2 - x([1, 1:end-1]) .* x([2:end, end]); end
github
HidekiKawahara/SparkNG-master
closeI2k0xi0.m
.m
SparkNG-master/src/closeI2k0xi0.m
129
utf_8
106882da17683d26bcbe66801e17795a
function out = closeI2k0xi0(t,Tw,td) out = -r(t-Tw)+r(t+Tw)+r(t-td-Tw)-r(t-td+Tw); function rout = r(x) rout = double(x.*(x>0));
github
HidekiKawahara/SparkNG-master
signal2logArea.m
.m
SparkNG-master/src/signal2logArea.m
959
utf_8
82344b850fa30bbc3d4b20845e0f129e
function logArea = signal2logArea(x) % by Hideki Kawahara % This is only a quick and dirty hack. Please refer to proper reference % for estimating vocal tract area function. % 18/Jan./2014 % This is valid only for signals sampled at 8000Hz. n = length(x); w = blackman(n); ww = w/sqrt(sum(w.^2)); fftl = 2^ceil(log2(n)); %x = [0;x(2:end)-0.925*x(1:end-1)]; x = [0;diff(x)]; pw = abs(fft(x.*ww,fftl)).^2; lpw = log(pw+sum(pw)/fftl/1000); lpwn = lpw-mean(lpw); theta = (0:fftl-1)/fftl*2*pi; %c1 = 2*sum(cos(theta(:)).*lpwn)/fftl; %c2 = sum(cos(2*theta(:)).*lpwn)/fftl; % This may not be necessary. %pwc = real(exp(lpwn-c1*cos(theta(:))-c2*cos(2*theta(:)))); pwc = real(exp(lpwn-0.5*cos(theta(:))+0.5*cos(2*theta(:)))); ac = real(ifft(pwc)); [alp,err,k] = levinson(ac,9); s = ref2area(-k); logArea = log(s); end function s = ref2area(k) n = length(k); s = zeros(n+1,1); s(end) = 1; for ii = n:-1:1 s(ii) = s(ii+1)*(1-k(ii))/(1+k(ii)); end; end
github
HidekiKawahara/SparkNG-master
simulatedFilterBank.m
.m
SparkNG-master/src/simulatedFilterBank.m
4,335
utf_8
a6ae00763c4ae00e1f23d759d6b2a59d
function filterBankStr = simulatedFilterBank(sgram,fx,bankType) % Filter bank simulator based on FFT power spectrum % 22/Dec./2013 by Hideki Kawahara % This simulation is rough approximation. Please refer to the original % papers for serious scientific applications. This routine is provided "as % is" and no warranty. % This is a sample code. Use this as you like. sgram = cumsum(sgram); fLow = 50; tickFrequencyList = [50 70 100 150 200 300 400 500 700 1000 1500 2000 3000 4000 5000 7000 10000 15000 20000]; filterBankStr.tickLabelList = char({'50';'70';'100';'150';'200';'300';'400';'500'; ... '700';'1000';'1500';'2000';'3000';'4000';'5000';'7000';'10000';'15000';'20000'}); switch bankType case 'third' logFrequencyAxis = fLow*2.0.^(0:1/24:log2(fx(end)/fLow)-1/6)'; fxUpper = logFrequencyAxis*2^(1/6); fxLower = logFrequencyAxis*2^(-1/6); upperCumPower = interp1(fx,sgram,fxUpper,'linear','extrap'); lowerCumPower = interp1(fx,sgram,fxLower,'linear','extrap'); filterBankStr.filteredSgramRectangle = upperCumPower-lowerCumPower; sgram = cumsum(filterBankStr.filteredSgramRectangle); upperCumPower = interp1(logFrequencyAxis,sgram,fxUpper,'linear','extrap'); lowerCumPower = interp1(logFrequencyAxis,sgram,fxLower,'linear','extrap'); filterBankStr.filteredSgramTriangle = upperCumPower-lowerCumPower; filterBankStr.fcList = logFrequencyAxis; case 'ERB' logFrequencyAxis = fLow*2.0.^(0:1/24:log2(fx(end)/fLow)-1/6)'; ERBofLogFrequencyAxis = freq2ERBprv(logFrequencyAxis); ERBFrequencyAxis = (0:200)'/200*(ERBofLogFrequencyAxis(end)-ERBofLogFrequencyAxis(1)) ... +ERBofLogFrequencyAxis(1); logFrequencyAxisTmp = interp1(ERBofLogFrequencyAxis,logFrequencyAxis,ERBFrequencyAxis,'linear','extrap'); %fxUpper = logFrequencyAxis*2^(1/6); fxUpper = interp1(ERBofLogFrequencyAxis,logFrequencyAxis,ERBFrequencyAxis+0.5,'linear','extrap'); fxLower = interp1(ERBofLogFrequencyAxis,logFrequencyAxis,ERBFrequencyAxis-0.5,'linear','extrap'); upperCumPower = interp1(fx,sgram,fxUpper,'linear','extrap'); lowerCumPower = interp1(fx,sgram,fxLower,'linear','extrap'); filterBankStr.filteredSgramRectangle = upperCumPower-lowerCumPower; sgram = cumsum(filterBankStr.filteredSgramRectangle); upperCumPower = interp1(logFrequencyAxisTmp,sgram,fxUpper,'linear','extrap'); lowerCumPower = interp1(logFrequencyAxisTmp,sgram,fxLower,'linear','extrap'); filterBankStr.filteredSgramTriangle = upperCumPower-lowerCumPower; filterBankStr.fcList = logFrequencyAxisTmp; case 'Bark' logFrequencyAxis = fLow*2.0.^(0:1/24:log2(fx(end)/fLow)-1/6)'; ERBofLogFrequencyAxis = freq2BarkPrv(logFrequencyAxis); ERBFrequencyAxis = (0:200)'/200*(ERBofLogFrequencyAxis(end)-ERBofLogFrequencyAxis(1)) ... +ERBofLogFrequencyAxis(1); logFrequencyAxisTmp = interp1(ERBofLogFrequencyAxis,logFrequencyAxis,ERBFrequencyAxis,'linear','extrap'); fxUpper = interp1(ERBofLogFrequencyAxis,logFrequencyAxis,ERBFrequencyAxis+0.5,'linear','extrap'); fxLower = interp1(ERBofLogFrequencyAxis,logFrequencyAxis,ERBFrequencyAxis-0.5,'linear','extrap'); upperCumPower = interp1(fx,sgram,fxUpper,'linear','extrap'); lowerCumPower = interp1(fx,sgram,fxLower,'linear','extrap'); filterBankStr.filteredSgramRectangle = upperCumPower-lowerCumPower; sgram = cumsum(filterBankStr.filteredSgramRectangle); upperCumPower = interp1(logFrequencyAxisTmp,sgram,fxUpper,'linear','extrap'); lowerCumPower = interp1(logFrequencyAxisTmp,sgram,fxLower,'linear','extrap'); filterBankStr.filteredSgramTriangle = upperCumPower-lowerCumPower; filterBankStr.fcList = logFrequencyAxisTmp; end; fxTrim = (0:length(filterBankStr.fcList)-1)/(length(filterBankStr.fcList)-1)* ... (filterBankStr.fcList(end)-filterBankStr.fcList(1))+filterBankStr.fcList(1); filterBankStr.ticLocationList = interp1(filterBankStr.fcList,fxTrim,tickFrequencyList,'linear','extrap'); end function erbAxis = freq2ERBprv(axisInHz) erbAxis=21.4*log10(0.00437*axisInHz+1); end function barkAxis = freq2BarkPrv(axisInHz) barkAxis = 26.81./(1+1960.0./axisInHz)-0.53; end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_Dehaze.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_Dehaze.m
266
utf_8
4b067c548346575b612c62b29b3795b6
%% dehaze % I, input image, balanced % T, transmission map % J, haze removal result function [ J ] = Lee_Dehaze( I, T, A) J = ( I - repmat(reshape(A,[1,1,3]),size(I,1),size(I,2)))./repmat(T,[1,1,size(I,3)])+repmat(reshape(A,[1,1,3]),size(I,1),size(I,2)); end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_Get_A.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_Get_A.m
178
utf_8
26dfea8bfdf18ebcd99a254d8c6e2ee6
%% estimate A based on Retinex Theory % I, input image % A, atmospheric color function [ A ] = Lee_Get_A( I ) A = get_atmosphere(im2double(I), get_dark_channel(I, 25)); end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Get_Dx.m
.m
Author---Dehazing-via-Graph-Cut-master/Get_Dx.m
877
utf_8
51085ba282ca9bd4bc0cb00757ff9262
%% a tool % I, input image % step, 1 - D is the minimal map of each channel. % 2 - D is eroded. % 3 - D is dark channel. % r, mask radius function [ D ] = Get_Dx( I, step, r ) %% prepare [m,n,c] = size(I); if nargin <= 2 r = ceil(0.05*min(m,n)); end if nargin <= 1 step = 3; end %% step 1. channel min only if c == 1 B = I; else B = min(I(:,:,1),I(:,:,2)); B = min(I(:,:,3),B); end if step <= 1 D = B; return; end %% step 2. erode se=strel('disk',r); D=imerode(B,se); if step <= 2 return; end %% step 3. refine L = get_laplacian(I); U = speye(size(L)); lambda = 0.0001; A = L + lambda * U; b = lambda * D(:); D_refine = A \ b; D_refine = reshape(D_refine, m, n); D = D_refine; end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_Get_WhiteI.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_Get_WhiteI.m
302
utf_8
d3d2d3cb4266414c933c8b7648b7630e
%% white balance based on Retinex theory % I, input image % I, output image, balanced function [ Iw ] = Lee_Get_WhiteI( I ) [~,~,c] = size(I); A = Lee_Get_A(I); if c==3 Iw(:,:,1) = I(:,:,1) ./ A(1); Iw(:,:,2) = I(:,:,2) ./ A(2); Iw(:,:,3) = I(:,:,3) ./ A(3); else Iw = I./A; end end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_CompressT.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_CompressT.m
958
utf_8
9e44c77a5e30caea42e52df5be57c39e
%% compress T % T, input trans map, [0,1] % num, finial range of T % type, mapping method % inverse, bool, inverse_mapping % T, output trans map, [1,num] function [ T ] = Lee_CompressT( T, num, type, inverse ) % prepare if nargin <= 3 inverse = 0; end if nargin <= 2 type = 'linear'; end gamma = 0.22; % linear if strcmp(type,'linear') && (~inverse) T = round( (num-1)*T+1 ); end % sin if strcmp(type,'sin') && (~inverse) T = round( (num-1)*sind(T*90)+1 ); end % gamma if strcmp(type,'gamma') && (~inverse) T = round( (num-1)*T.^gamma+1 ); end % inverse linear if strcmp(type,'linear') && (inverse) T = (T-1)/(num-1); end % inverse sin if strcmp(type,'sin') && (inverse) T = asind((T-1)/(num-1))/90; end % inverse gamma if strcmp(type,'gamma') && (inverse) T = ((T-1)/(num-1)).^(1/gamma); end end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_EnergyMinimization_Dehazing.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_EnergyMinimization_Dehazing.m
1,267
utf_8
b36e8db76aa57382bc2a7bc5f6e5e0c0
%% energy minimization dehazing % I, input image % J, dehazing result % T, transmission map % A, atmospheric color % Cache, Intermediate data function [ J, T, A, Cache] = Lee_EnergyMinimization_Dehazing( I ) Cache = cell(3,1); %% atmospheric color estimate fprintf('est. atmospheric color...\n'); A = Lee_Get_A(I); t1=clock; Iw = Lee_Get_WhiteI(I); %% solve initial T, alpha-exphansion fprintf('est. initial transmission map...\n'); tic; Labels = GraphCut(min(1,max(0,Get_Dx(Iw,1)))); fprintf('Graph cut takes %0.2f second\n',toc); T_initial = 1-(Labels-1)/31; %% regularization fprintf('regularization...\n'); %T_reg=Lee_Regularization(Iw,T_initial,10000,5); tic; T_reg=wls_optimization(T_initial,I,0.01); fprintf('regularization takes %0.2f second\n',toc); %% brighter haze_factor = 1.1; gamma = 1; T = (T_reg + (haze_factor-1) )/haze_factor; fprintf('dehazing...\n'); J1 = Lee_Dehaze(Iw,T,[1,1,1]).*repmat(reshape(A,[1,1,3]),size(I,1),size(I,2)); J = J1; J(J>0)=J(J>0).^gamma; t2=clock; runtime = etime(t2,t1); fprintf('overall run-time is %0.2f second\n',runtime); %% Intermediate data save Cache{1} = T_initial; end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_Get_InitialTrans.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_Get_InitialTrans.m
831
utf_8
e3c52673984def91292bda4b75d902bf
%% initial transmission map estimated by alpha-expansion % Iw, input image, white balanced % T, output map, initial transmission map function [ LS ] = Lee_Get_InitialTrans( I, mask ) %% prepare [m,n,~] = size(I); pixel_num = m*n; if nargin <= 1 mask = ceil(0.05*min(m,n)); end %% Label set T_lb = im2uint8(1-Get_Dx(I,1)); Bias = int32(getneighbors(strel('disk',mask))); LS = Lee_Cut(T_lb,Bias); %% cut sc = Lee_Get_Laplacian(Get_Dx(I,1),1); sc(logical(tril(sc))) = 0; dc = double([any(LS(1:75,:));any(LS(76:256,:))]); h = BK_Create(pixel_num); BK_SetUnary(h,-10000000*dc); BK_SetNeighbors(h,-sc); e = BK_Minimize(h); L = BK_GetLabeling(h); label = double(reshape(L,[m,n])); figure;imshow(label-1); colormap(jet);axis off; end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_Regularization.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_Regularization.m
478
utf_8
56aba4f6f1eb448ab6e24df861aff744
%% regularization % I, input image % T, input transmission map % lambda, weight of data term % r, neighbor range, laplacian matrix function [ T ] = Lee_Regularization( I, T_initial, lambda, r ) L = Lee_Get_Laplacian(I,r); U = speye(size(L)); A = L + lambda * U; b = lambda * T_initial(:); T = A \ b; T = reshape(T, size(T_initial)); % T = T - min(T(:)); % T = T./max(T(:)); % T = (max(T_initial(:))-min(T_initial(:)))*T+min(T(:)); end
github
Lilin2015/Author---Dehazing-via-Graph-Cut-master
Lee_AlphaExpansion.m
.m
Author---Dehazing-via-Graph-Cut-master/Lee_AlphaExpansion.m
348
utf_8
d61e28f7b3ef8b4f016f56d0b15563d7
%% initial transmission map estimated by alpha-expansion % I, input image % label_num, range of label % label, output map, initial transmission map function [ T ] = Lee_AlphaExpansion( I, label_num ) %% prepare I = im2double(I); %% form label set of each pixel B = round((label_num-1)*Get_Dx(I,1))+1; T = Dehaze(B); end
github
ecntrk/BuildHDR-master
fish2Cube.m
.m
BuildHDR-master/source/fish2Cube.m
722
utf_8
1b49758d50d007ae991eebf855b0dbb4
function [op] = fish2Cube(img) % takes a fisheye HDR image and coverts it into latitude longitude format [h w z] = size(img); op = zeros(h, 2*h, 3); r = floor(h/2); for j = 1:h for i = 1:2*h theta = (pi/(2*h))*(j-1);% Pi /2*h phi = (pi/h)*(i-1); % 2*Pi / w a = r*cos(theta); x = round(a*cos(phi)+ r +0.5); y = round(a*sin(phi)+ r +0.5); if sanityCheckFlip(x,y,w,h)==true %arg = [theta, phi, a, cos(phi), x,y]; %disp(arg); op ( h-j +1, (2*h)-i+1, :) = img(y, x, :); end end end end function isTrue = sanityCheckFlip(x,y, w, h) if isnan(x) || isnan (y) isTrue = false; return; end if (x>=1) && (x <=w) if (y>=1) && (y <= h) isTrue = true; else isTrue = false; return; end else isTrue = false; return; end end
github
MBradbury/Packages-master
syntax_test_matlab.m
.m
Packages-master/Matlab/syntax_test_matlab.m
4,860
utf_8
a003a307f9054a4ae45ebe5ce22f2829
% SYNTAX TEST "Packages/Matlab/Matlab.sublime-syntax" %--------------------------------------------- % Matlab OOP test classdef (Sealed = false) classname < baseclass % <- keyword.other % ^ variable.parameter % ^ keyword.operator.symbols % ^ constant.language % ^ entity.name.class % ^ entity.other.inherited-class properties (SetAccess = private, GetAccess = true) % ^ keyword.other % ^ variable.parameter % ^ constant.language % ^ variable.parameter PropName end % ^ keyword.control methods % ^ keyword.other methodName end events % ^ keyword.other EventName end enumeration % ^ keyword.other EnumName end end %--------------------------------------------- % Syntax brackets/parens punctuation test x = [ 1.76 ] % <- source.matlab meta.variable.other.valid.matlab % ^ source.matlab keyword.operator.symbols.matlab % ^ source.matlab punctuation.section.brackets.begin.matlab % ^^^^ source.matlab meta.brackets.matlab constant.numeric.matlab % ^ source.matlab punctuation.section.brackets.end.matlab xAprox = fMetodoDeNewton( xi ) % <- source.matlab meta.variable.other.valid.matlab % ^ source.matlab keyword.operator.symbols.matlab % ^ source.matlab meta.variable.other.valid.matlab % ^ source.matlab punctuation.section.parens.begin.matlab % ^ source.matlab meta.parens.matlab meta.variable.other.valid.matlab % ^ source.matlab punctuation.section.parens.end.matlab %--------------------------------------------- % Block comment test % Success case %{ x = 5 % ^ source.matlab comment.block.percentage.matlab %} % Invalid block %{ Not start of block comment % ^ comment.line.percentage.matlab x = 5 % ^ keyword.operator.symbols.matlab %} %{ %} Not end of block % ^ comment.block.percentage.matlab x = 5 % ^ comment.block.percentage.matlab %} x = 5 %{ not block comment % ^ keyword.operator.symbols.matlab x = 5 % ^ constant.numeric.matlab %--------------------------------------------- % Function function y = average(x) % <- keyword.other % ^ variable.parameter.output.function.matlab % ^^^^^^^ entity.name.function.matlab % ^ variable.parameter.input.function.matlab if ~isvector(x) % ^ keyword.operator.symbols.matlab error('Input must be a vector') end y = sum(x)/length(x); end function [m,s] = stat(x) % <- keyword.other % ^ variable.parameter.output.function.matlab % ^ -variable.parameter.output.function.matlab % ^ variable.parameter.output.function.matlab % ^^^^ entity.name.function.matlab % ^ variable.parameter.input.function.matlab n = length(x); m = sum(x)/n; s = sqrt(sum((x-m).^2/n)); end function m = avg(x,n) % ^^^ entity.name.function.matlab % ^ variable.parameter.input.function.matlab % ^ variable.parameter.input.function.matlab m = sum(x)/n; end %--------------------------------------------- % Numbers 1 % <- constant.numeric.matlab .1 % <- constant.numeric.matlab 1.1 % <- constant.numeric.matlab .1e1 % <- constant.numeric.matlab 1.1e1 % <- constant.numeric.matlab 1e1 % <- constant.numeric.matlab 1i % <- constant.numeric.matlab 1j % <- constant.numeric.matlab 1e2j % <- constant.numeric.matlab %--------------------------------------------- % transpose a = a' % is the conjugate and transpose % ^ -keyword.operator.transpose.matlab % ^ keyword.operator.transpose.matlab a = a.' % is the transpose % ^ -keyword.operator.transpose.matlab % ^^ keyword.operator.transpose.matlab x = a[3]' + b(4)' % is the conjugate and transpose % ^ keyword.operator.transpose.matlab % ^ keyword.operator.transpose.matlab %--------------------------------------------- % String a = '%' a = '.' % .' % ^^^ comment.line.percentage.matlab 'a'a' % ^ string.quoted.single.matlab invalid.illegal.unescaped-quote.matlab %^ string.quoted.single.matlab punctuation.definition.string.begin.matlab % ^ string.quoted.single.matlab % ^ string.quoted.single.matlab punctuation.definition.string.end.matlab regexprep(outloc,'.+\\','') % ^ punctuation.definition.string.begin.matlab % ^^ meta.parens.matlab string.quoted.single.matlab % ^^ constant.character.escape.matlab % ^ punctuation.definition.string.end.matlab s1="00:06:57"; % ^ punctuation.definition.string.begin.matlab % ^^^^^^^^ string.quoted.double.matlab % ^ punctuation.definition.string.end.matlab
github
trebledawson/Machine-Learning-Examples-master
gradient_descent_linear.m
.m
Machine-Learning-Examples-master/MATLAB/gradient_descent_linear.m
1,717
utf_8
d17f41d66df43bcb55c1abde34728561
% ***************************************** % % Linear Regression using Gradient Descent % % Glenn Dawson % % 2017-09-15 % % ***************************************** % theta = [0;0]; alpha = 0.0001; gradient_descent(theta,alpha); % Arguments: 1x2 vector theta, scalar alpha function m=gradient_descent(theta,alpha) % Random data generation data_b = 7; % Vertical displacement of random data data_m = 2; % Slope of random data n = 100; % Number of random samples noise = rand(n,1); % Data noise x = rand(n,1).*10; % Random x values y = data_b + data_m*x + noise; % Corresponding y data % Gradient Descent Algorithm cost = 1; % Initialize cost variable costs = []; % Initialize costs for plot while abs(cost) > 0.0001 % Minimize cost function sum = [0 ; 0]; % Initialize sum of diff(H(theta)) cost = 0; % Reset cost for i=1:length(x) % Compute cost and sum of H and J X = [1;x(i)]; sum = sum + (theta'*X - y(i))*X; cost = cost + (theta'*X - y(i)); end costs = [costs abs(cost)]; % For plotting costs over iterations theta = theta - alpha*sum; % Update theta end % Plot results subplot(211) plot(x,y,'.'); title('Plot of randomly generated data (with linear regression)') hold on plot(x,theta(2)*x+theta(1)); hold off subplot(212) plot(costs,'.'); title('Cost function values over gradient descent iterations'); % Return final values of theta m=theta; end
github
trebledawson/Machine-Learning-Examples-master
simple_perceptron_.m
.m
Machine-Learning-Examples-master/MATLAB/simple_perceptron_.m
5,850
utf_8
4ac884bce86bd763fe3d8efad73c8713
% ********************************************* % % Perceptron Discriminant with Gradient Descent % % Glenn Dawson % % 2017-10-03 % % ********************************************* % clear all; clc % ################################################################### % % MAIN % % ################################################################### % tic % Generate three linearly separable distributions cases = 1000; omega1 = mvnrnd([1.2,3.25],[0.1 0;0 0.1],cases); omega2 = mvnrnd([3.5,3.75],[0.1 0;0 0.1],cases); omega3 = mvnrnd([2.75,1.5],[0.1 0;0 0.1],cases); % omega4 = mvnrnd([5.1,2],[0.1 0;0 0.1],cases); omega = [omega1;omega2;omega3]; % omega = [omega1;omega2;omega3;omega4]; label1 (1:cases) = 1; label2 (1:cases) = 2; label3 (1:cases) = 3; % label4 (1:cases) = 4; labels = [label1,label2,label3]; % labels = [label1,label2,label3,label4]; subplot(221) plot(omega1(:,1),omega1(:,2),'b.') title('Randomly Generated, Linearly-Separable Data') hold on grid plot(omega2(:,1),omega2(:,2),'r.') plot(omega3(:,1),omega3(:,2),'g.') % plot(omega4(:,1),omega4(:,2),'m.') % Plot perceptron classification subplot(222) class = simple_perceptron(omega,omega,labels); title('Simple Perceptron Classification of Data') hold on; for i=1:length(class) if class(i) == 1 plot(omega(i,1),omega(i,2),'b.') elseif class(i) == 2 plot(omega(i,1),omega(i,2),'r.') elseif class(i) == 3 plot(omega(i,1),omega(i,2),'g.') % elseif class(i) == 4 % plot(omega(i,1),omega(i,2),'m.') else plot(omega(i,1),omega(i,2),'k.') end end grid; % Plot decision boundary map subplot(224) ZX = 0:0.025:4.5; ZY = 0:0.025:5; % ZX = 0:0.025:7; % ZY = 0:0.025:5; Z = zeros(length(ZX)*length(ZY),2); for j=1:length(ZX) for k=1:length(ZY) var = ((j-1)*length(ZY) + k); Z(var,1) = ZX(j); Z(var,2) = ZY(k); end end Zclass = simple_perceptron(Z,omega,labels); title('Simple Perceptron Decision Boundary Map') hold on; for i=1:length(Zclass) if Zclass(i) == 1 plot(Z(i,1),Z(i,2),'b.') elseif Zclass(i) == 2 plot(Z(i,1),Z(i,2),'r.') elseif Zclass(i) == 3 plot(Z(i,1),Z(i,2),'g.') elseif Zclass(i) == 4 plot(Z(i,1),Z(i,2),'m.') else plot(Z(i,1),Z(i,2),'k.') end end grid; % Calculate error rate K = 10; indices = crossvalind('Kfold',labels,K); cp = classperf(labels); for i = 1:K test = (indices == i); train = ~test; class = simple_perceptron(omega(test,:),omega(train,:),labels(train)); classperf(cp,class,test); end fprintf('The k-fold cross-validated error rate is : %d.\n', cp.ErrorRate); toc % ################################################################### % % END OF MAIN % % ################################################################### % % ******************************************************************* % Simple perceptron classifier function % ---------- % Arguments: % omega is a set of data that % ******************************************************************* function class = simple_perceptron(omega_test,omega_train,labels) % Re-sort training data omega1 = omega_train((labels==1),:); omega1NOT = omega_train((labels~=1),:); omega2 = omega_train((labels==2),:); omega2NOT = omega_train((labels~=2),:); omega3 = omega_train((labels==3),:); omega3NOT = omega_train((labels~=3),:); % omega4 = omega_train((labels==4),:); % omega4NOT = omega_train((labels~=4),:); % Calculate decision boundaries with gradient descent W1 = gradient_descent(omega1,omega1NOT); W2 = gradient_descent(omega2,omega2NOT); W3 = gradient_descent(omega3,omega3NOT); % W4 = gradient_descent(omega4,omega4NOT); % Use decision boundaries as weights for perceptron nodes and use node % decisions to classify test instance [instances, ~] = size(omega_test); classifications = zeros(instances,1); for i=1:instances G1 = node(omega_test(i,:),W1); G2 = node(omega_test(i,:),W2); G3 = node(omega_test(i,:),W3); % G4 = node(omega_test(i,:),W4); [~,index] = max([G1,G2,G3]); % [~,index] = max([G1,G2,G3,G4]); classifications(i) = index; end class = classifications; end % ******************************************************************* % Gradient descent function to find decision boundary between any two % classes % ---------- % Arguments: % X1 and X2 are Nx2 matrices of training data % ******************************************************************* function W = gradient_descent(X1, X2) % Create vertical matrix of data X = vertcat(X1, X2); % Create vertical matrix of labels Y1 (1:length(X1),1) = 1; Y2 (1:length(X2),1) = -1; Y = vertcat(Y1, Y2); % Gradient descent algorithm w = [1;0;0]; eta = 0.03; delta_w = [1;0;0]; check = 1; count = 0; % while pdist([delta_w';0 0 0]) > 0.0001 while check > 0.1 % Find set of misclassified samples Xm_IDX = []; for i=1:length(X) Xi = [1;X(i,1);X(i,2)]; if Y(i)*(w'*Xi) < 0 Xm_IDX = [Xm_IDX i]; end end % Use misclassified samples to update w sum = [0;0;0]; for i=1:length(Xm_IDX) sum = sum + Y(Xm_IDX(i))*[1;X(Xm_IDX(i),1);X(Xm_IDX(i),2)]; end delta_w = eta*sum; w = w + delta_w; check = pdist([delta_w';0 0 0]); count = count + 1; end W = w; end % ******************************************************************* % Perceptron node function % ---------- % Arguments: % X is an 1x2 vector of input data % W is a 3x1 vector of input weights % A and B are the choices the node can make % ******************************************************************* function Z = node(X,W) Z = W(1)*1 + W(2)*X(1) + W(3)*X(2); end
github
trebledawson/Machine-Learning-Examples-master
bayes_classifier_1d.m
.m
Machine-Learning-Examples-master/MATLAB/bayes_classifier_1d.m
1,537
utf_8
2b8ad7bbdc53785fbf4b1ff745c7e778
% ***************************** % % Bayes Classifier in 1-D Data % % Glenn Dawson % % 2017-09-21 % % ***************************** % % Argument(s): % S is the nth term of Z, where 1 < n < 1000 function P=bayes(S); % Generate two 1-D data sets MU1 = 0.5; % Mean of class 1 SIGMA1 = 0.05; % Stdev of class 1 MU2 = 0.6; % Mean of class 2 SIGMA2 = 0.05; % Stdev of class 2 omega1 = normrnd(MU1,SIGMA1,[1 1000]); omega2 = normrnd(MU2,SIGMA2,[1 1000]); % Plot the generated data histograms histogram(omega1,100); hold on; histogram(omega2,100); hold off; % Calculate the mean and sigma of generated data mu1 = mean(omega1); mu2 = mean(omega2); sigma1 = std(omega1); sigma2 = std(omega2); % Generate test data from originally defined normal distributions Z = []; for i=1:1000 Zomega1 = normrnd(MU1,SIGMA1); Zomega2 = normrnd(MU2,SIGMA2); switch randi(2) case 1 Z = [Z Zomega1]; case 2 Z = [Z Zomega2]; end end % Plot test data histogram hold on histogram(Z,100); hold off; % Calculate P(Z|omegaj) G1 = normpdf(Z(S),mu1,sigma1); G2 = normpdf(Z(S),mu2,sigma2); % Given P(Z(S))=1 and P(omegaj)=0.5, calculate Bayesian probability density P1 = (G1*0.5)/1; P2 = (G2*0.5)/1; % Choose greatest Bayesian probability density % Return [nth element of Z ; P(omega1|Z) ; P(omega2|Z) ; Classification] switch max([P1 P2]) case P1 P=[Z(S); P1; P2; 1]; case P2 P=[Z(S); P1; P2; 2]; end end
github
trebledawson/Machine-Learning-Examples-master
naive_bayes.m
.m
Machine-Learning-Examples-master/MATLAB/naive_bayes.m
2,004
utf_8
7904c91fe8ec3c46367a7b39f5b1efca
% ********************************* % % Naive Bayes Classifier % % Glenn Dawson % % 2017-09-25 % % ********************************* % % Input arguments: % X is an MxN matrix of training data whose rows correspond to instances % and whose columns correspond to features % Y is an Mx1 vector containing known classifications of the corresponding % rows of X % Z is an LxN matrix of test data whose rows correspond to instances and % whose columns correspond to features % Output: % A 1xL vector containing classifications for all instances in Z function p=naive_bayes(X,Y,Z) sizeX = size(X); sizeZ = size(Z); class_count = unique(Y); % Mu and sigma are of form ____(class, feature) mu = zeros(length(class_count),sizeX(2)); sigma = zeros(length(class_count),sizeX(2)); for i=1:length(class_count) % For each class... X_class = X(find(Y==i),:); size_class = size(X_class); % Calculate mu and sigma for each feature means = mean(X_class); stdev = std(X_class); for j=1:length(means) mu(i,j) = means(j); sigma(i,j) = stdev(j); end end % Create and populate an array consisting of classifications of Z classifications = zeros(1,length(sizeZ(1))); for i=1:sizeZ(1) % For each instance... posterior = zeros(1,length(class_count)); for j=1:length(class_count) % For each class... % Compute prior based on frequency of class in data prior = numel(X(find(Y==j),:))/numel(X); % Calculate the class conditional likelihoods likelihood = zeros(1,sizeX(2)); for k=1:sizeX(2) % For each feature... likelihood(k) = normpdf(Z(i,k), mu(j,k), sigma(j,k)); end % Compute the posterior distribution assuming class-conditional % feature independence posterior(j) = prior * prod(likelihood); end [~,max_index] = max(posterior); classifications(i) = max_index; end p=classifications; end
github
trebledawson/Machine-Learning-Examples-master
cumulative_distgen.m
.m
Machine-Learning-Examples-master/MATLAB/cumulative_distgen.m
1,095
utf_8
ef76ed24c7a725f8fa678b5a5093daee
% ******************************************************************* % % Cumulative Distribution Function of Arbitrary Discrete Distribution % % Glenn Dawson % % 2017-09-19 % % ******************************************************************* % % Arguments: % X is a vector containing normalized probabilities % Y is an integer representing the number of samples to be drawn from X % Returns: % 1-by-Y vector m ~ X function m=cumdistgen(X, Y) % Generate a sample from the distribution sample = []; for i=1:Y r=rand; % Generate a random number {0 1} cumdist=0; % Reset cumulative distribution j=1; % Counter for X while r >= cumdist cumdist = cumdist + X(j); % Add X(j) probability to extant sum j = j+1; % Increment to X(j+1) end sample = [sample (j-1)]; % Add chosen element of X to sample end % Return sample m=sample;
github
trebledawson/Machine-Learning-Examples-master
knn.m
.m
Machine-Learning-Examples-master/MATLAB/knn.m
1,359
utf_8
9b717edc42e5085b87beb356a887653b
% ********************* % % K-Nearest Neighbor % % Glenn Dawson % % 2017-09-27 % % ********************* % function p=knn(X,Y,Z,K) % Input arguments: % X is an MxN matrix of training data whose rows correspond to instances % and whose columns correspond to features % Y is an Mx1 vector containing known classifications of the corresponding % rows of X % Z is an LxN matrix of test data whose rows correspond to instances and % whose columns correspond to features % K is the KNN parameter % Output: % A 1xL vector containing classifications for all instances in Z [X_instances, ~]=size(X); [Z_instances, ~]=size(Z); classifications = zeros(1,Z_instances); for i=1:Z_instances % For all test instances... % Find distances from test instance to training instance distances = zeros(1,X_instances); for j=1:X_instances % For all training instances... distances(j) = pdist([X(j,:);Z(i,:)],'euclidean'); end % Find the K nearest neighbors K_nearest = zeros(1,K); for j=1:K [~,min_index] = min(distances); K_nearest(j) = min_index; distances(min_index) = 0; end % Find the nearest neighbor nearest = mode(K_nearest); % Select the class corresponding to the nearest neighbor classifications(i) = Y(nearest); end p=classifications; end
github
smart-media-lab/Visual-saliency-detection-in-image-using-ant-colony-optimisation-and-local-phase-coherence-master
saliency_EL_2010_main.m
.m
Visual-saliency-detection-in-image-using-ant-colony-optimisation-and-local-phase-coherence-master/saliency_EL_2010_main.m
17,931
utf_8
858cf5d707b0ff0dbb43b03c9a8d2c01
function saliency_EL_2010_main % % This is a demo program of the paper L. Ma, J. Tian, and W. Yu, % "Visual saliency detection in image using ant colony optimisation and local phase coherence," % Electronics Letters, Vol. 46, Jul. 2010, pp. 1066-1068. % clear all; close all; clc; % Load test image img_in = double(imread('test.jpg')); % Perform saliency detection mask = func_saliency_aco_phase(img_in); % Write the output saliency map imwrite(uint8(mask),'test_saliency_map.bmp','bmp'); %------------------------------------------------------------------------- %------------------------------Inner Function ---------------------------- %------------------------------------------------------------------------- function p = func_saliency_aco_phase(img) [nrow, ncol] = size(img); img_1D = func_2D_LexicoOrder(img); % initialization p = 0.001 .* ones(size(img)); p_1D = func_2D_LexicoOrder(p); delta_p = zeros(size(img)); delta_p_1D = func_2D_LexicoOrder(delta_p); %paramete setting alpha = 1; beta = 2; phi = 0.3; ant_total_num = round(sqrt(nrow*ncol)); ant_current_row = zeros(ant_total_num, 1); % record the location of ant ant_current_col = zeros(ant_total_num, 1); % record the location of ant rand('state', sum(clock)); temp = rand(ant_total_num, 2); ant_current_row = round(1 + (nrow-1) * temp(:,1)); %row index ant_current_col = round(1 + (ncol-1) * temp(:,2)); %column index ant_current_val = img_1D((ant_current_row-1).*ncol+ant_current_col); % build v matrix v = zeros(size(img)); v_norm = 0; for rr =1:nrow for cc=1:ncol %defination of clique temp1 = [rr-2 cc-1; rr-2 cc+1; rr-1 cc-2; rr-1 cc-1; rr-1 cc; rr-1 cc+1; rr-1 cc+2; rr cc-1]; temp2 = [rr+2 cc+1; rr+2 cc-1; rr+1 cc+2; rr+1 cc+1; rr+1 cc; rr+1 cc-1; rr+1 cc-2; rr cc+1]; temp0 = find(temp1(:,1)>=1 & temp1(:,1)<=nrow & temp1(:,2)>=1 & temp1(:,2)<=ncol & temp2(:,1)>=1 & temp2(:,1)<=nrow & temp2(:,2)>=1 & temp2(:,2)<=ncol); temp11 = temp1(temp0, :); temp22 = temp2(temp0, :); temp00 = zeros(size(temp11,1)); for kk = 1:size(temp11,1) temp00(kk) = abs(img(temp11(kk,1), temp11(kk,2))-img(temp22(kk,1), temp22(kk,2))); end if size(temp11,1) == 0 v(rr, cc) = 0; v_norm = v_norm + v(rr, cc); else v(rr, cc) = max(max(temp00)); end end end % Calculate the phase v = func_phasecong(img); v_1D = func_2D_LexicoOrder(v); % System setup ant_move_step_within_iteration = 300; total_iteration_num = 3; search_clique_mode = 8; for nIteration = 1: total_iteration_num ant_current_path_row = zeros(ant_total_num,ant_move_step_within_iteration); ant_current_path_col = zeros(ant_total_num,ant_move_step_within_iteration); ant_current_path_val = zeros(ant_total_num,ant_move_step_within_iteration); ant_current_path_row(:,1) = ant_current_row; ant_current_path_col(:,1) = ant_current_col; ant_current_path_val(:,1) = ant_current_val; for nMoveStep = 1: ant_move_step_within_iteration-1 if search_clique_mode == 4 ant_search_range_row = [ant_current_row-1, ant_current_row, ant_current_row+1, ant_current_row]; ant_search_range_col = [ant_current_col, ant_current_col+1, ant_current_col, ant_current_col-1]; elseif search_clique_mode == 8 ant_search_range_row = [ant_current_row-1, ant_current_row-1, ant_current_row-1, ant_current_row, ant_current_row,ant_current_row+1, ant_current_row+1, ant_current_row+1]; ant_search_range_col = [ant_current_col-1, ant_current_col, ant_current_col+1, ant_current_col-1, ant_current_col+1, ant_current_col-1, ant_current_col, ant_current_col+1]; end ant_current_row_extend = padarray(ant_current_row, [0 search_clique_mode-1],'replicate','post'); ant_current_col_extend = padarray(ant_current_col, [0 search_clique_mode-1],'replicate','post'); ant_search_range_val = zeros(ant_total_num,search_clique_mode); %replace the positions our of the image's range temp = (ant_search_range_row>=1) & (ant_search_range_row<=nrow) & (ant_search_range_col>=1) & (ant_search_range_col<=ncol); ant_search_range_row = temp.*ant_search_range_row + (~temp).*ant_current_row_extend; ant_search_range_col = temp.*ant_search_range_col + (~temp).*ant_current_col_extend; ant_search_range_transit_prob_h = zeros(size(ant_search_range_val)); ant_search_range_transit_prob_p = zeros(size(ant_search_range_val)); for ii=1:search_clique_mode ant_search_range_transit_prob_h(:,ii) = v_1D((ant_search_range_row(:,ii)-1).*ncol+ant_search_range_col(:,ii)); ant_search_range_transit_prob_p(:,ii) = p_1D((ant_search_range_row(:,ii)-1).*ncol+ant_search_range_col(:,ii)); end temp = (ant_search_range_transit_prob_h.^alpha) .* (ant_search_range_transit_prob_p.^beta); temp_sum = ((sum(temp'))'); temp_sum = padarray(temp_sum, [0 search_clique_mode-1],'replicate','post'); ant_search_range_transit_prob = temp ./ temp_sum; % generate a random number to determine the next position. rand('state', sum(100*clock)); temp = rand(ant_total_num,1); temp = padarray(temp, [0 search_clique_mode-1],'replicate','post'); temp = cumsum(ant_search_range_transit_prob,2)>=temp; temp = padarray(temp, [0 1],'pre'); temp = (diff(temp,1,2)==1); temp_row = (ant_search_range_row .* temp)'; [ii, jj, vv] = find(temp_row); ant_next_row = vv; temp_col = (ant_search_range_col .* temp)'; [ii, jj, vv] = find(temp_col); ant_next_col = vv; ant_current_path_val(:,nMoveStep+1) = img_1D((ant_next_row-1).*ncol+ant_next_col); ant_current_path_row(:,nMoveStep+1) = ant_next_row; ant_current_path_col(:,nMoveStep+1) = ant_next_col; ant_current_row = ant_next_row; ant_current_col = ant_next_col; ant_current_val = img_1D((ant_current_row-1).*ncol+ant_current_col); rr = ant_current_row; cc = ant_current_col; delta_p_1D((rr-1).*ncol+cc,1) = 1; delta_p = func_LexicoOrder_2D(delta_p_1D, nrow, ncol); end % end of nMoveStep p = (1-phi).*p + delta_p.*v.*(v>mean(v(:))); p_1D = func_2D_LexicoOrder(p); delta_p = zeros(size(img)); delta_p_1D = func_2D_LexicoOrder(delta_p); end % end of nIteration % Perform normalization to be range [0,255]; p = p./(sum(sum(p))); p = (p-min(p(:)))./(max(p(:))-min(p(:))).*255; %------------------------------------------------------------------------- %------------------------------Inner Function ---------------------------- %------------------------------------------------------------------------- % Convert data from 2D format to 1D format function result = func_2D_LexicoOrder(x) temp = x'; result = temp(:); %------------------------------------------------------------------------- %------------------------------Inner Function ---------------------------- %------------------------------------------------------------------------- % Convert data from 1D format to 2D format function result = func_LexicoOrder_2D(x, nRow, nColumn) result = reshape(x, nColumn, nRow)'; %------------------------------------------------------------------------- %------------------------------Inner Function ---------------------------- %------------------------------------------------------------------------- % Calculate local phase coherence at each pixel position function phaseCongruency = func_phasecong(im) sze = size(im); if nargin < 2 nscale = 3; % Number of wavelet scales. end if nargin < 3 norient = 6; % Number of filter orientations. end if nargin < 4 minWaveLength = 3; % Wavelength of smallest scale filter. end if nargin < 5 mult = 2; % Scaling factor between successive filters. end if nargin < 6 sigmaOnf = 0.55; % Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's transfer function % in the frequency domain to the filter center frequency. end if nargin < 7 dThetaOnSigma = 1.7; % Ratio of angular interval between filter orientations % and the standard deviation of the angular Gaussian % function used to construct filters in the % freq. plane. end if nargin < 8 k = 3.0; % No of standard deviations of the noise energy beyond the % mean at which we set the noise threshold point. % standard deviation to its maximum effect % on Energy. end if nargin < 9 cutOff = 0.4; % The fractional measure of frequency spread % below which phase congruency values get penalized. end g = 10; % Controls the sharpness of the transition in the sigmoid % function used to weight phase congruency for frequency % spread. epsilon = .0001; % Used to prevent division by zero. thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the % angular Gaussian function used to % construct filters in the freq. plane. imagefft = fft2(im); % Fourier transform of image sze = size(imagefft); rows = sze(1); cols = sze(2); zero = zeros(sze); totalEnergy = zero; % Matrix for accumulating weighted phase % congruency values (energy). totalSumAn = zero; % Matrix for accumulating filter response % amplitude values. orientation = zero; % Matrix storing orientation with greatest % energy for each pixel. estMeanE2n = []; % Pre-compute some stuff to speed up filter construction x = ones(rows,1) * (-cols/2 : (cols/2 - 1))/(cols/2); y = (-rows/2 : (rows/2 - 1))' * ones(1,cols)/(rows/2); radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre. radius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle % so that taking the log of the radius will % not cause trouble. theta = atan2(-y,x); % Matrix values contain polar angle. % (note -ve y is used to give +ve % anti-clockwise angles) sintheta = sin(theta); costheta = cos(theta); clear x; clear y; clear theta; % save a little memory % The main loop... for o = 1:norient, % For each orientation. % disp(['Processing orientation ' num2str(o)]); angl = (o-1)*pi/norient; % Calculate filter angle. wavelength = minWaveLength; % Initialize filter wavelength. sumE_ThisOrient = zero; % Initialize accumulator matrices. sumO_ThisOrient = zero; sumAn_ThisOrient = zero; Energy_ThisOrient = zero; EOArray = []; % Array of complex convolution images - one for each scale. ifftFilterArray = []; % Array of inverse FFTs of filters ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine. dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine. dtheta = abs(atan2(ds,dc)); % Absolute angular distance. spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component. for s = 1:nscale, % For each scale. % Construct the filter - first calculate the radial filter component. fo = 1.0/wavelength; % Centre frequency of filter. rfo = fo/0.5; % Normalised radius from centre of frequency plane % corresponding to fo. logGabor = exp((-(log(radius/rfo)).^2) / (2 * log(sigmaOnf)^2)); logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter % back to zero (undo the radius fudge). filter = logGabor .* spread; % Multiply by the angular spread to get the filter. filter = fftshift(filter); % Swap quadrants to move zero frequency % to the corners. ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power ifftFilterArray = [ifftFilterArray ifftFilt]; % record ifft2 of filter % Convolve image with even and odd filters returning the result in EO EOfft = imagefft .* filter; % Do the convolution. EO = ifft2(EOfft); % Back transform. EOArray = [EOArray, EO]; % Record convolution result An = abs(EO); % Amplitude of even & odd filter response. sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses. sumE_ThisOrient = sumE_ThisOrient + real(EO); % Sum of even filter convolution results. sumO_ThisOrient = sumO_ThisOrient + imag(EO); % Sum of odd filter convolution results. if s == 1 % Record the maximum An over all scales maxAn = An; else maxAn = max(maxAn, An); end if s==1 EM_n = sum(sum(filter.^2)); % Record mean squared filter value at smallest end % scale. This is used for noise estimation. wavelength = wavelength * mult; % Finally calculate Wavelength of next filter end % ... and process the next scale % Get weighted mean filter response vector, this gives the weighted mean phase angle. XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon; MeanE = sumE_ThisOrient ./ XEnergy; MeanO = sumO_ThisOrient ./ XEnergy; for s = 1:nscale, EO = submat(EOArray,s,cols); % Extract even and odd filter E = real(EO); O = imag(EO); Energy_ThisOrient = Energy_ThisOrient ... + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE); end medianE2n = median(reshape(abs(submat(EOArray,1,cols)).^2,1,rows*cols)); meanE2n = -medianE2n/log(0.5); estMeanE2n = [estMeanE2n meanE2n]; noisePower = meanE2n/EM_n; % Estimate of noise power. % Now estimate the total energy^2 due to noise % Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj)) EstSumAn2 = zero; for s = 1:nscale EstSumAn2 = EstSumAn2+submat(ifftFilterArray,s,cols).^2; end EstSumAiAj = zero; for si = 1:(nscale-1) for sj = (si+1):nscale EstSumAiAj = EstSumAiAj + submat(ifftFilterArray,si,cols).*submat(ifftFilterArray,sj,cols); end end EstNoiseEnergy2 = 2*noisePower*sum(sum(EstSumAn2)) + 4*noisePower*sum(sum(EstSumAiAj)); tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 ); T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold T = T/1.7; % Empirical rescaling of the estimated noise effect to % suit the PC_2 phase congruency measure Energy_ThisOrient = max(Energy_ThisOrient - T, zero); % Apply noise threshold width = sumAn_ThisOrient ./ (maxAn + epsilon) / nscale; % Now calculate the sigmoidal weighting function for this orientation. weight = 1.0 ./ (1 + exp( (cutOff - width)*g)); % Apply weighting Energy_ThisOrient = weight.*Energy_ThisOrient; % Update accumulator matrix for sumAn and totalEnergy totalSumAn = totalSumAn + sumAn_ThisOrient; totalEnergy = totalEnergy + Energy_ThisOrient; if(o == 1), maxEnergy = Energy_ThisOrient; featType = E + i*O; else change = Energy_ThisOrient > maxEnergy; orientation = (o - 1).*change + orientation.*(~change); featType = (E+i*O).*change + featType.*(~change); maxEnergy = max(maxEnergy, Energy_ThisOrient); end end % For each orientation phaseCongruency = totalEnergy ./ (totalSumAn + epsilon); orientation = orientation * (180 / norient); featType = featType*i; % Rotate feature phase angles by 90deg so that 0 % phase corresponds to a step edge (this is a % fudge I must have something the wrong way % around somewhere) phaseCongruency = exp(phaseCongruency); phaseCongruency = phaseCongruency./(sum(sum(phaseCongruency))); %------------------------------------------------------------------------- %------------------------------Inner Function ---------------------------- %------------------------------------------------------------------------- function a = submat(big,i,cols) a = big(:,((i-1)*cols+1):(i*cols));
github
Akki369/Fetal-Heart-Beat_ECG-master
miso.m
.m
Fetal-Heart-Beat_ECG-master/miso.m
6,192
utf_8
bde7f1d4a03b4774df86d2cbcfb5d3ab
% MATLAB code for MISO system clc; clear all; close all; load('foetal_ecg.dat'); x=foetal_ecg; % time signal; timesig=x(:,1); % abdnomial signals abdomin1=x(:,2); abdomin2=x(:,3); abdomin3=x(:,4); abdomin4=x(:,5); abdomin5=x(:,6); %thoriad signals thoirad1=x(:,7); thoirad2=x(:,8); thoirad3=x(:,9); figure subplot(5,1,1); plot(timesig,abdomin1); title('abdomin1'); xlabel('time[s]'); ylabel('amplitude mV'); subplot(5,1,2); plot(timesig,abdomin2); title('abdomin2'); ylabel('amplitude mV'); xlabel('time'); subplot(5,1,3); plot(timesig,abdomin3); title('abdomin3'); xlabel('time'); ylabel('amplitude mV'); subplot(5,1,4); plot(timesig,abdomin4); title('abdomin4'); xlabel('time'); ylabel('amplitude mV'); subplot(5,1,5); plot(timesig,abdomin5); title('abdomin5'); xlabel('time'); ylabel('amplitude mV'); figure subplot(3,1,1); plot(timesig,thoirad1,'r'); title('thoirad1'); xlabel('time'); ylabel('amplitude mV'); subplot(3,1,2); plot(timesig,thoirad2,'r'); title('thoirad2'); xlabel('time'); ylabel('amplitude mV'); subplot(3,1,3); plot(timesig,thoirad3,'r'); title('thoirad3'); xlabel('time'); ylabel('amplitude mV'); d=(abdomin1+abdomin2+abdomin3+abdomin4+abdomin5)/5; a=thoirad1; a1=thoirad2; a2=thoirad3; %% Applying for LMS Algorithm mue= 0.00000002; nord=12; X=convm(a,nord); X1=convm(a1,nord); X2=convm(a2,nord); %Applying LMS algorithm using lms basic function. [A,A1,A2,E1,y1] = lms1(X,X1,X2,d,mue,nord); %% Applying for NLMS Algorithm beta=0.005; nord=12; X=convm(a,nord); X1=convm(a1,nord); X2=convm(a2,nord); %Applying NLMS algorithm using lms basic function. [A,A1,A2,E2,y2] = nlms1(X,X1,X2,d,beta,nord); %% Applying for LLMS Algorithm mu=0.0000002; gammax=0.001; nord=12; X=convm(a,nord); X1=convm(a1,nord); X2=convm(a2,nord); %Applying LMS algorithm using llms basic function. [W,W1,W2,E3,y3] = llms1(X,X1,X2,d,mu,gammax,nord); %% Plotting signals % Fetus+mothers signal figure subplot(2,1,1) plot(timesig,d(1:2500),'r-'); hold on; plot(timesig,d(1:2500),'k--'); hold on; plot(timesig,d(1:2500),'b:'); hold on; title('Fetus + Mothers output'); xlabel('time[sec]'); ylabel('Amplitude [mV]'); legend('MISO-LMS','MISO-NLMS','MISO-LLMS') %% Mothers signal subplot(2,1,2) plot(timesig,a(1:2500),'r-'); hold on; plot(timesig,a(1:2500),'k--'); hold on; plot(timesig,a(1:2500),'b:'); hold on; title('Mothers ECG for MISO'); xlabel('time[sec]'); ylabel('Amplitude [mV]'); legend('MISO-LMS','MISO-NLMS','MISO-LLMS'); %% Filter output figure subplot(2,1,1) plot(timesig,y1(1:2500),'r-'); hold on; plot(timesig,y2(1:2500),'k--'); hold on; plot(timesig,y3(1:2500),'b:'); hold on; title('filter output'); xlabel('time[sec]'); ylabel('Amplitude [mV]'); %axis([0 1 -10 10]) legend('MISO-LMS','MISO-NLMS','MISO-LLMS') %% Fetus signal subplot(2,1,2) plot(timesig,E1(1:2500),'r-'); hold on; plot(timesig,E2(1:2500),'k--'); hold on; plot(timesig,E3(1:2500),'b:'); hold on; title('Fetus Output for MISO'); xlabel('time[sec]'); ylabel('Amplitude [mV]'); %axis([0 1 -10 10]) legend('MISO-LMS','MISO-NLMS','MISO-LLMS') MISO Calling Functions: CONVM Function: function[X] = convm(x,p) N = length(x)+2*p-2; x = x(:); xpad = [zeros(p-1,1);x;zeros(p-1,1)]; for i=1:p X(:,i)=xpad(p-i+1 :N-i+1); end; LMS Function: function [A,A1,A2,E,y] = lms1(X,X1,X2,d,mu,nord,a0) [M,N] = size(X); [M1,N1] = size(X1); [M2,N2] = size(X2); if nargin < 7, a0 = zeros(1,N); end a0 = a0(:).'; y1= zeros(1,M); y2= zeros(1,M1); y3= zeros(1,M2); E=zeros(1,M); E1=zeros(1,M1); E2=zeros(1,M2); A=zeros(size(X)); A1=zeros(size(X1)); A2=zeros(size(X2)); y1(1)= a0*X(1,:).'; y2(1)= a0*X1(1,:).'; y3(1)= a0*X2(1,:).'; E(1) = d(1) - a0*X(1,:).'; A(1,:) = a0 + mu*E(1)*conj(X(1,:)); A1(1,:) = a0 + mu*E(1)*conj(X1(1,:)); A2(1,:) = a0 + mu*E(1)*conj(X2(1,:)); if M>1 for k=2:M-nord+1; y1(k) = A(k-1,:)*X(k,:).'; y2(k) = A1(k-1,:)*X1(k,:).'; y3(k) = A2(k-1,:)*X2(k,:).'; y(k)=(y1(k)+y2(k)+y3(k))/3; E(k) = d(k) - y(k); A(k,:) = A(k-1,:) + mu*E(k)*conj(X(k,:)); A1(k,:) = A1(k-1,:) + mu*E(k)*conj(X1(k,:)); A2(k,:) = A2(k-1,:) + mu*E(k)*conj(X2(k,:)); end; end; NLMS Function: function [A,A1,A2,E,y] = nlms1(X,X1,X2,d,beta,nord,a0) [M,N] = size(X); [M1,N1] = size(X1); [M2,N2] = size(X2); if nargin < 7, a0 = zeros(1,N); end a0 = a0(:).'; y1= zeros(1,M); y2= zeros(1,M1); y3= zeros(1,M2); E=zeros(1,M); E1=zeros(1,M1); E2=zeros(1,M2); A=zeros(size(X)); A1=zeros(size(X1)); A2=zeros(size(X2)); y1(1)= a0*X(1,:).'; y2(1)= a0*X1(1,:).'; y3(1)= a0*X2(1,:).'; E(1) = d(1) - a0*X(1,:).'; DEN=X(1,:)*X(1,:)'+X1(1,:)*X1(1,:)' +X2(1,:)*X2(1,:)'+ 0.0001; A(1,:) = a0 + beta/DEN*E(1)*conj(X(1,:)); A1(1,:) = a0 + beta/DEN*E(1)*conj(X1(1,:)); A2(1,:) = a0 + beta/DEN*E(1)*conj(X2(1,:)); if M>1 for k=2:M-nord+1; y1(k) = A(k-1,:)*X(k,:).'; y2(k) = A1(k-1,:)*X1(k,:).'; y3(k) = A2(k-1,:)*X2(k,:).'; y(k)=(y1(k)+y2(k)+y3(k))/3; E(k) = d(k) - y(k); DEN=X(k,:)*X(k,:)'+X1(k,:)*X1(k,:)' +X2(k,:)*X2(k,:)'+ 0.0001; A(k,:) = A(k-1,:) + beta/DEN*E(k)*conj(X(k,:)); A1(k,:) = A1(k-1,:) +beta/DEN*E(k)*conj(X1(k,:)); A2(k,:) = A2(k-1,:) + beta/DEN*E(k)*conj(X2(k,:)); end; end; LLMS Function: function [W,W1,W2,E,y] = llms1(X,X1,X2,d,mu,gammax,nord,a0) [M,N] = size(X); [M1,N1] = size(X1); [M2,N2] = size(X2); if nargin < 8, a0 = zeros(1,N); end a0 = a0(:).'; y1= zeros(1,M); y2= zeros(1,M1); y3= zeros(1,M2); E=zeros(1,M); E1=zeros(1,M1); E2=zeros(1,M2); W=zeros(size(X)); W1=zeros(size(X1)); W2=zeros(size(X2)); y1(1)= a0*X(1,:).'; y2(1)= a0*X1(1,:).'; y3(1)= a0*X2(1,:).'; E(1) = d(1) - a0*X(1,:).'; W(1,:) = (1 -mu*gammax)*a0 + mu*E(1)*conj(X(1,:)); W1(1,:) = (1 -mu*gammax)*a0 + mu*E(1)*conj(X1(1,:)); W2(1,:) = (1 -mu*gammax)*a0 + mu*E(1)*conj(X2(1,:)); if M>1 for k=2:M-nord+1; y1(k) = W(k-1,:)*X(k,:).'; y2(k) = W1(k-1,:)*X1(k,:).'; y3(k) = W2(k-1,:)*X2(k,:).'; y(k)=(y1(k)+y2(k)+y3(k))/3; E(k) = d(k) - y(k); W(k,:) = (1 -mu*gammax)*W(k-1,:) + mu*E(k)*conj(X(k,:)); W1(k,:) = (1 -mu*gammax)*W1(k-1,:) + mu*E(k)*conj(X1(k,:)); W2(k,:) = (1 -mu*gammax)*W2(k-1 ,:) + mu*E(k)*conj(X2(k,:)); end; end;
github
Akki369/Fetal-Heart-Beat_ECG-master
lms.m
.m
Fetal-Heart-Beat_ECG-master/lms.m
471
utf_8
6463d6fe97da6c97d5d3c82887fe12aa
%%LMS CODE ALGORITHM FOR THE SOURSE CODE %% function [A,E,Y] = lms(x,d,mu,nord) %lms function X=convm(x,nord); [M,N]=size(X); if nargin < 5, a0 = zeros(1,N); end a0=a0(:).'; Y(1)=a0*X(1,:).'; E(1)=d(1) - Y(1); A(1,:) = a0 + mu*E(1)*conj(X(1,:)); if M>1 for k=2:M-nord+1; Y(k,:)=A(k-1,:)*X(k,:).';%ouput equation E(k,:) = d(k) - Y(k,:);%error signal A(k,:)=A(k-1,:)+mu*E(k)*conj(X(k,:));%update equation end; end; %%
github
Akki369/Fetal-Heart-Beat_ECG-master
nlms.m
.m
Fetal-Heart-Beat_ECG-master/nlms.m
605
utf_8
ca8d2bd60f55008f0eafdacc616dc731
%%NLMS CALGORITHM FOR THE SOURSE CODE %% function [A,E,Y] = nlms(x,d,beta,nord,a0) X=convm(x,nord); [M,N]=size(X); if nargin < 5, a0 = zeros(1,N); end %initialization a0=a0(:).'; Y(1)=a0*X(1,:).'; E(1)=d(1) - a0*X(1,:).'; DEN=X(1,:)*X(1,:)'+0.0001; A(1,:) = a0 + beta/DEN*E(1)*conj(X(1,:)); if M>1 for k=2:M-nord+1; Y(k)=A(k-1,:)*X(k,:).';%output equation E(k) = d(k) - A(k-1,:)*X(k,:).';%error signal DEN=X(k,:)*X(k,:)'+0.0001;%normalizing the input signal A(k,:)=A(k-1,:)+ beta/DEN*E(k)*conj(X(k,:));%update equation end; end;
github
Akki369/Fetal-Heart-Beat_ECG-master
llms.m
.m
Fetal-Heart-Beat_ECG-master/llms.m
477
utf_8
2525bb025827cc4f752992a4655b27e8
%%LLMS FUNCTION OF THE SOURSE CODE %% function [A,E,Y]= llms(x,d,mu,gama,nord,a0) X=convm(x,nord); [M,N]=size(X); if nargin < 6, a0 = zeros(1,N); end a0=a0(:).'; Y(1)=a0*X(1,:).'; E(1)=d(1) - Y(1); A(1,:)=(1-mu*gama)*a0+mu*E(1)*conj(X(1,:)); if M>1 for k=2:M-nord+1; Y(k,:)=A(k-1,:)*X(k,:).';%output signal E(k,:) = d(k) - Y(k,:);%error signal A(k,:)=(1-mu*gama)*A(k-1,:)+mu*E(k)*conj(X(k,:));%update equation end; end; %%
github
rsln-s/algebraic-distance-on-hypergraphs-master
laplacianfun.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/JacobiSmooth/laplacianfun.m
1,910
utf_8
229c2016c307956cb856011c9c0b33d7
% function [MAT,NODES,DN]=laplacianfun(NPTS,[BCS]) % % Generates a discretized Laplacian operator in any arbitrarily % large number of dimensions. % Input: % NPTS - Vector containing the number of points per dimension of % the discretization % [BCS] - Boundary conditions for each variable. 0 [default] % gives dirchlet (to a point not included in our grid). 1 % gives periodic bc's in that variable. % Output: % MAT - Discretized Laplacian % NODES - Location of the nodes % DN - Number of dirchlet neighbors per node (does not work % with Neuman bc's). % % by: Chris Siefert <[email protected]> % Last Update: 07/05/06 <siefert> function [MAT,NODES,DN]=laplacianfun(NPTS,varargin) % Check for BC's OPTS=nargin-1; if (OPTS >= 1) BCS=varargin{1}; else BCS=0*NPTS;end if (OPTS == 2) SCALE=varargin{2}; else SCALE=false;end % Pull Constants NDIM=length(NPTS); N=prod(NPTS); % Sanity check if (length(NPTS) ~= length(BCS)) fprintf('Error: Size mismatch between NPTS and BCS\n');return;end % Compute jumps (normal) JUMP=cumprod(NPTS);JUMP=[1,JUMP(1:NDIM)]; % Compute jumps (periodic) JP=JUMP(2:NDIM+1)-JUMP(1:NDIM); % Diagonal MAT=2*NDIM*speye(N,N); % Assembly for I=1:NDIM, VEC=repmat([ones(JUMP(I)*(NPTS(I)-1),1);zeros(JUMP(I),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JUMP(I)); MAT=MAT-spdiags([zeros(JUMP(I),1);VEC],JUMP(I),N,N) - spdiags([VEC;zeros(JUMP(I),1)],-JUMP(I),N,N); if(BCS(I)==1) VEC=repmat([ones(JUMP(I),1);zeros(JUMP(I)*(NPTS(I)-1),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JP(I)); MAT=MAT-spdiags([zeros(JP(I),1);VEC],JP(I),N,N) - spdiags([VEC;zeros(JP(I),1)],-JP(I),N,N); end end % Nodal Location NODES=[1:NPTS(1)]'; for I=2:NDIM, SZ=size(NODES,1); NODES=[repmat(NODES,NPTS(I),1),reshape(repmat(1:NPTS(I),SZ,1),SZ*NPTS(I),1)]; end % Dirchlet Neighbors DEG=sum(abs(MAT)>0,2); DN=full(max(DEG)-DEG);
github
rsln-s/algebraic-distance-on-hypergraphs-master
getDiag.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/JacobiSmooth/getDiag.m
186
utf_8
e2f27271754871c6760c2c1c494d8291
%Use getDiag() as "setup" function for MatlabSmoother function D = getDiag(A) D = sparse(diag(diag(A))); %first call generates vector of diagonal, second call puts that in a matrix end
github
rsln-s/algebraic-distance-on-hypergraphs-master
jacobi.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/JacobiSmooth/jacobi.m
991
utf_8
01fa09d69d259ca0c60e2bda75e6ce4a
% function [sol,resnrm]=jacobi(A,x0,b,omega,nits,[varargin]) % % Runs SOR-Jacobi iteration on the matrix A to solve % the equation Ax=b. Assumes A is sparse. Uses % initial guess x0. % -------------- Parameters --------------- % A = Matrix of the system. % x0 = Initial guess % b = RHS of system % D = Matrix diagonal % omega = Over-relaxation parameter % nits = Iteration cap % -------------- Outputs ------------------ % sol = Solution vector from SOR-Jacobi % resrnm= Norm of the residual from the solution sol % %Use jacobi() as "solve" function for MatlabSmoother % CMS: First time through function [sol] = jacobi(A, x0, b, D) omega = 0.9; nits = 5; % CMS: Later interface %function [sol]=jacobi2(A,x0,b,D,omega,nits) % Initializations sol = x0; n = size(A, 1); % Compute Initial Residual Norm resnrm(1) = norm(b - A * x0); for I = 1:nits, %disp(['MATLAB: Running Jacobi iteration #', I]); % Next iterate sol = sol + omega * (D \ (b - A * sol)); end end
github
rsln-s/algebraic-distance-on-hypergraphs-master
laplacianfun.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/CustomP/laplacianfun.m
1,910
utf_8
229c2016c307956cb856011c9c0b33d7
% function [MAT,NODES,DN]=laplacianfun(NPTS,[BCS]) % % Generates a discretized Laplacian operator in any arbitrarily % large number of dimensions. % Input: % NPTS - Vector containing the number of points per dimension of % the discretization % [BCS] - Boundary conditions for each variable. 0 [default] % gives dirchlet (to a point not included in our grid). 1 % gives periodic bc's in that variable. % Output: % MAT - Discretized Laplacian % NODES - Location of the nodes % DN - Number of dirchlet neighbors per node (does not work % with Neuman bc's). % % by: Chris Siefert <[email protected]> % Last Update: 07/05/06 <siefert> function [MAT,NODES,DN]=laplacianfun(NPTS,varargin) % Check for BC's OPTS=nargin-1; if (OPTS >= 1) BCS=varargin{1}; else BCS=0*NPTS;end if (OPTS == 2) SCALE=varargin{2}; else SCALE=false;end % Pull Constants NDIM=length(NPTS); N=prod(NPTS); % Sanity check if (length(NPTS) ~= length(BCS)) fprintf('Error: Size mismatch between NPTS and BCS\n');return;end % Compute jumps (normal) JUMP=cumprod(NPTS);JUMP=[1,JUMP(1:NDIM)]; % Compute jumps (periodic) JP=JUMP(2:NDIM+1)-JUMP(1:NDIM); % Diagonal MAT=2*NDIM*speye(N,N); % Assembly for I=1:NDIM, VEC=repmat([ones(JUMP(I)*(NPTS(I)-1),1);zeros(JUMP(I),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JUMP(I)); MAT=MAT-spdiags([zeros(JUMP(I),1);VEC],JUMP(I),N,N) - spdiags([VEC;zeros(JUMP(I),1)],-JUMP(I),N,N); if(BCS(I)==1) VEC=repmat([ones(JUMP(I),1);zeros(JUMP(I)*(NPTS(I)-1),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JP(I)); MAT=MAT-spdiags([zeros(JP(I),1);VEC],JP(I),N,N) - spdiags([VEC;zeros(JP(I),1)],-JP(I),N,N); end end % Nodal Location NODES=[1:NPTS(1)]'; for I=2:NDIM, SZ=size(NODES,1); NODES=[repmat(NODES,NPTS(I),1),reshape(repmat(1:NPTS(I),SZ,1),SZ*NPTS(I),1)]; end % Dirchlet Neighbors DEG=sum(abs(MAT)>0,2); DN=full(max(DEG)-DEG);
github
rsln-s/algebraic-distance-on-hypergraphs-master
customP.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/CustomP/customP.m
697
utf_8
abfd3776eeb8f084a395e9b9ce8e65cb
%Prototype function to generate unsmoothed P from aggregates function [P, Nullspace, KeepNodes] = createP(A, KeepNodesFine) N = size(A, 1); Nkeep = length(KeepNodesFine); OK_IDX = setdiff(1:N, KeepNodesFine); A_OK = A(OK_IDX,OK_IDX); h = muelu('setup', A_OK, 'max levels', 2, 'coarse: max size', int32(size(A, 1) / 3)); P_OK = muelu('get', h, 1, 'P'); muelu('cleanup', h); % NOTE To Ray: This probably won't work for multiple PDEs/NODE P = sparse(N, size(P_OK, 2) + Nkeep); P(OK_IDX, 1:size(P_OK, 2)) = P_OK; P(KeepNodesFine, size(P_OK, 2) + 1:end) = speye(Nkeep, Nkeep); % NOTE: Totally Faking nullspace Nullspace = ones(size(P_OK, 2), 1); KeepNodes=size(P_OK, 2) + [1:Nkeep]; end
github
rsln-s/algebraic-distance-on-hypergraphs-master
laplacianfun.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/Brick/laplacianfun.m
1,910
utf_8
229c2016c307956cb856011c9c0b33d7
% function [MAT,NODES,DN]=laplacianfun(NPTS,[BCS]) % % Generates a discretized Laplacian operator in any arbitrarily % large number of dimensions. % Input: % NPTS - Vector containing the number of points per dimension of % the discretization % [BCS] - Boundary conditions for each variable. 0 [default] % gives dirchlet (to a point not included in our grid). 1 % gives periodic bc's in that variable. % Output: % MAT - Discretized Laplacian % NODES - Location of the nodes % DN - Number of dirchlet neighbors per node (does not work % with Neuman bc's). % % by: Chris Siefert <[email protected]> % Last Update: 07/05/06 <siefert> function [MAT,NODES,DN]=laplacianfun(NPTS,varargin) % Check for BC's OPTS=nargin-1; if (OPTS >= 1) BCS=varargin{1}; else BCS=0*NPTS;end if (OPTS == 2) SCALE=varargin{2}; else SCALE=false;end % Pull Constants NDIM=length(NPTS); N=prod(NPTS); % Sanity check if (length(NPTS) ~= length(BCS)) fprintf('Error: Size mismatch between NPTS and BCS\n');return;end % Compute jumps (normal) JUMP=cumprod(NPTS);JUMP=[1,JUMP(1:NDIM)]; % Compute jumps (periodic) JP=JUMP(2:NDIM+1)-JUMP(1:NDIM); % Diagonal MAT=2*NDIM*speye(N,N); % Assembly for I=1:NDIM, VEC=repmat([ones(JUMP(I)*(NPTS(I)-1),1);zeros(JUMP(I),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JUMP(I)); MAT=MAT-spdiags([zeros(JUMP(I),1);VEC],JUMP(I),N,N) - spdiags([VEC;zeros(JUMP(I),1)],-JUMP(I),N,N); if(BCS(I)==1) VEC=repmat([ones(JUMP(I),1);zeros(JUMP(I)*(NPTS(I)-1),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JP(I)); MAT=MAT-spdiags([zeros(JP(I),1);VEC],JP(I),N,N) - spdiags([VEC;zeros(JP(I),1)],-JP(I),N,N); end end % Nodal Location NODES=[1:NPTS(1)]'; for I=2:NDIM, SZ=size(NODES,1); NODES=[repmat(NODES,NPTS(I),1),reshape(repmat(1:NPTS(I),SZ,1),SZ*NPTS(I),1)]; end % Dirchlet Neighbors DEG=sum(abs(MAT)>0,2); DN=full(max(DEG)-DEG);
github
rsln-s/algebraic-distance-on-hypergraphs-master
simpleAggregation.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/Brick/simpleAggregation.m
665
utf_8
ba56479c76377500d24e55d361220920
%A function implementing a very simple aggregation scheme. %Triplets of nodes with consecutive IDs are grouped together. %Should simulate brick with some set of parameters? function agg = simpleAggregation(A) [m, n] = size(A); nVerts = m; %number of rows -> number of nodes nAggs = nVerts / 3; vertToAgg = int32(zeros([nVerts, 1])); for i = 1:nVerts vertToAgg(i) = int32((i - 2) / 3); end rootNodes = int32(zeros([nAggs, 1])); for i = 1:nAggs rootNodes(i) = int32(i * 3 - 2); end aggSizes = int32(zeros([nAggs, 1])); for i = 1:nAggs aggSizes(i) = int32(3); end agg = constructAggregates(nVerts, nAggs, vertToAgg, rootNodes, aggSizes); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
laplacianfun.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/ReentrantDemo/laplacianfun.m
1,910
utf_8
229c2016c307956cb856011c9c0b33d7
% function [MAT,NODES,DN]=laplacianfun(NPTS,[BCS]) % % Generates a discretized Laplacian operator in any arbitrarily % large number of dimensions. % Input: % NPTS - Vector containing the number of points per dimension of % the discretization % [BCS] - Boundary conditions for each variable. 0 [default] % gives dirchlet (to a point not included in our grid). 1 % gives periodic bc's in that variable. % Output: % MAT - Discretized Laplacian % NODES - Location of the nodes % DN - Number of dirchlet neighbors per node (does not work % with Neuman bc's). % % by: Chris Siefert <[email protected]> % Last Update: 07/05/06 <siefert> function [MAT,NODES,DN]=laplacianfun(NPTS,varargin) % Check for BC's OPTS=nargin-1; if (OPTS >= 1) BCS=varargin{1}; else BCS=0*NPTS;end if (OPTS == 2) SCALE=varargin{2}; else SCALE=false;end % Pull Constants NDIM=length(NPTS); N=prod(NPTS); % Sanity check if (length(NPTS) ~= length(BCS)) fprintf('Error: Size mismatch between NPTS and BCS\n');return;end % Compute jumps (normal) JUMP=cumprod(NPTS);JUMP=[1,JUMP(1:NDIM)]; % Compute jumps (periodic) JP=JUMP(2:NDIM+1)-JUMP(1:NDIM); % Diagonal MAT=2*NDIM*speye(N,N); % Assembly for I=1:NDIM, VEC=repmat([ones(JUMP(I)*(NPTS(I)-1),1);zeros(JUMP(I),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JUMP(I)); MAT=MAT-spdiags([zeros(JUMP(I),1);VEC],JUMP(I),N,N) - spdiags([VEC;zeros(JUMP(I),1)],-JUMP(I),N,N); if(BCS(I)==1) VEC=repmat([ones(JUMP(I),1);zeros(JUMP(I)*(NPTS(I)-1),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JP(I)); MAT=MAT-spdiags([zeros(JP(I),1);VEC],JP(I),N,N) - spdiags([VEC;zeros(JP(I),1)],-JP(I),N,N); end end % Nodal Location NODES=[1:NPTS(1)]'; for I=2:NDIM, SZ=size(NODES,1); NODES=[repmat(NODES,NPTS(I),1),reshape(repmat(1:NPTS(I),SZ,1),SZ*NPTS(I),1)]; end % Dirchlet Neighbors DEG=sum(abs(MAT)>0,2); DN=full(max(DEG)-DEG);
github
rsln-s/algebraic-distance-on-hypergraphs-master
modifyP.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/ReentrantDemo/modifyP.m
964
utf_8
6b61d2a8676b33a7f01f86ad361b4d98
%Function to demonstrate reentrant capability in muemex %Take a P from a default MueLu hierarchy and modify it %so that all nonzero values only have one significant figure function P = createP(A) %Create a separate hierarchy to get a fresh, default P disp('Generating inner hierarchy...'); newHier = muelu('setup', A, 'coarse: max size', 100, 'verbosity', 'none'); P = muelu('get', newHier, 1, 'P'); %This always gives the next prolongator, no matter what the current level # is disp('Done generating inner hierarchy.'); muelu('cleanup', newHier); %If not cleaned up, the inner hierarchy will stay in list of problems along with outer one [i, j, s] = find(P); for k = 1:length(s) placeVal = 10^floor(log10(s(k))); %If P(i) is 0.0513, placeVal will be 0.01. s(k) = placeVal * ceil(s(k) / placeVal); %Dividing by placeVal shifts the decimal representation so that exactly one digit is left of decimal place. end P = sparse(i, j, s); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
laplacianfun.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/UnsmoothedP/laplacianfun.m
1,910
utf_8
229c2016c307956cb856011c9c0b33d7
% function [MAT,NODES,DN]=laplacianfun(NPTS,[BCS]) % % Generates a discretized Laplacian operator in any arbitrarily % large number of dimensions. % Input: % NPTS - Vector containing the number of points per dimension of % the discretization % [BCS] - Boundary conditions for each variable. 0 [default] % gives dirchlet (to a point not included in our grid). 1 % gives periodic bc's in that variable. % Output: % MAT - Discretized Laplacian % NODES - Location of the nodes % DN - Number of dirchlet neighbors per node (does not work % with Neuman bc's). % % by: Chris Siefert <[email protected]> % Last Update: 07/05/06 <siefert> function [MAT,NODES,DN]=laplacianfun(NPTS,varargin) % Check for BC's OPTS=nargin-1; if (OPTS >= 1) BCS=varargin{1}; else BCS=0*NPTS;end if (OPTS == 2) SCALE=varargin{2}; else SCALE=false;end % Pull Constants NDIM=length(NPTS); N=prod(NPTS); % Sanity check if (length(NPTS) ~= length(BCS)) fprintf('Error: Size mismatch between NPTS and BCS\n');return;end % Compute jumps (normal) JUMP=cumprod(NPTS);JUMP=[1,JUMP(1:NDIM)]; % Compute jumps (periodic) JP=JUMP(2:NDIM+1)-JUMP(1:NDIM); % Diagonal MAT=2*NDIM*speye(N,N); % Assembly for I=1:NDIM, VEC=repmat([ones(JUMP(I)*(NPTS(I)-1),1);zeros(JUMP(I),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JUMP(I)); MAT=MAT-spdiags([zeros(JUMP(I),1);VEC],JUMP(I),N,N) - spdiags([VEC;zeros(JUMP(I),1)],-JUMP(I),N,N); if(BCS(I)==1) VEC=repmat([ones(JUMP(I),1);zeros(JUMP(I)*(NPTS(I)-1),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JP(I)); MAT=MAT-spdiags([zeros(JP(I),1);VEC],JP(I),N,N) - spdiags([VEC;zeros(JP(I),1)],-JP(I),N,N); end end % Nodal Location NODES=[1:NPTS(1)]'; for I=2:NDIM, SZ=size(NODES,1); NODES=[repmat(NODES,NPTS(I),1),reshape(repmat(1:NPTS(I),SZ,1),SZ*NPTS(I),1)]; end % Dirchlet Neighbors DEG=sum(abs(MAT)>0,2); DN=full(max(DEG)-DEG);
github
rsln-s/algebraic-distance-on-hypergraphs-master
createP.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/UnsmoothedP/createP.m
289
utf_8
3bb25e08b22327ef6cc67556b84c5df3
%Prototype function to generate unsmoothed P from aggregates function [Ptent, Nullspace] = createP(agg) Ptent = sparse(double(agg.nVertices), double(agg.nAggregates)); for i = 1:agg.nVertices Ptent(i, 1 + agg.vertexToAggID(i)) = 1; end Nullspace = ones(1, agg.nVertices); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
laplacianfun.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/Evolution/laplacianfun.m
1,910
utf_8
229c2016c307956cb856011c9c0b33d7
% function [MAT,NODES,DN]=laplacianfun(NPTS,[BCS]) % % Generates a discretized Laplacian operator in any arbitrarily % large number of dimensions. % Input: % NPTS - Vector containing the number of points per dimension of % the discretization % [BCS] - Boundary conditions for each variable. 0 [default] % gives dirchlet (to a point not included in our grid). 1 % gives periodic bc's in that variable. % Output: % MAT - Discretized Laplacian % NODES - Location of the nodes % DN - Number of dirchlet neighbors per node (does not work % with Neuman bc's). % % by: Chris Siefert <[email protected]> % Last Update: 07/05/06 <siefert> function [MAT,NODES,DN]=laplacianfun(NPTS,varargin) % Check for BC's OPTS=nargin-1; if (OPTS >= 1) BCS=varargin{1}; else BCS=0*NPTS;end if (OPTS == 2) SCALE=varargin{2}; else SCALE=false;end % Pull Constants NDIM=length(NPTS); N=prod(NPTS); % Sanity check if (length(NPTS) ~= length(BCS)) fprintf('Error: Size mismatch between NPTS and BCS\n');return;end % Compute jumps (normal) JUMP=cumprod(NPTS);JUMP=[1,JUMP(1:NDIM)]; % Compute jumps (periodic) JP=JUMP(2:NDIM+1)-JUMP(1:NDIM); % Diagonal MAT=2*NDIM*speye(N,N); % Assembly for I=1:NDIM, VEC=repmat([ones(JUMP(I)*(NPTS(I)-1),1);zeros(JUMP(I),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JUMP(I)); MAT=MAT-spdiags([zeros(JUMP(I),1);VEC],JUMP(I),N,N) - spdiags([VEC;zeros(JUMP(I),1)],-JUMP(I),N,N); if(BCS(I)==1) VEC=repmat([ones(JUMP(I),1);zeros(JUMP(I)*(NPTS(I)-1),1)],N/JUMP(I+1),1); VEC=VEC(1:N-JP(I)); MAT=MAT-spdiags([zeros(JP(I),1);VEC],JP(I),N,N) - spdiags([VEC;zeros(JP(I),1)],-JP(I),N,N); end end % Nodal Location NODES=[1:NPTS(1)]'; for I=2:NDIM, SZ=size(NODES,1); NODES=[repmat(NODES,NPTS(I),1),reshape(repmat(1:NPTS(I),SZ,1),SZ*NPTS(I),1)]; end % Dirchlet Neighbors DEG=sum(abs(MAT)>0,2); DN=full(max(DEG)-DEG);
github
rsln-s/algebraic-distance-on-hypergraphs-master
evolutionSoCFactory.m
.m
algebraic-distance-on-hypergraphs-master/packages/muelu/matlab/tests/Evolution/evolutionSoCFactory.m
3,244
utf_8
de6304ee1b7cdd865c0eea5c906940e0
%Prototype function to test evolution strength-of-connection % % reference: Algorithm 1, "Evolution Measure", p. 724 of % "A new perspective on strength measures in algebraic multigrid" % Luke Olson, Jacob Schroder, and Ray Tuminaro % Numerical Linear Algebra with Applications, Vol. 17, p 713-733, 2010 % doi 10.1002/nla.669 % % Notes: Dofs per node is hardwired to 1 % function [Graph, DofsPerNode, Filtering, S] = evolutionSoC(A, B) %TODO Should not be hardwired to 1. DofsPerNode = 1; % TODO get k from Parameter List % TODO get theta from Parameter List % TODO use lambda max estimate if it's available Graph.edges = logical(A); Graph.boundaryNodes = int32([]); % temporary matrix recording SoC measures S = sparse(A); D = diag(A); DinvA = diag(D)\A; lambdaMax = eigs(DinvA,1,'LM'); if exist('k') ~= 1 k = max(floor(lambdaMax),1); end if exist('theta') ~= 1 theta = 4.0; end Filtering = false; % If any connections are dropped, then Filtering must be true [m,n] = size(A); I = speye(m,n); deltaFn = zeros(m,1); e = zeros(m,1); % iterate over rows of A numDropped = 0; for ii=1:m e(ii) = 1; deltaFn(ii) = 1; z = deltaFn; % FIXME deep copy for jj=1:k %z = (I - 1/(k*lambdaMax)*DinvA)*z; z = z - 1/(k*lambdaMax)*(DinvA*z); end % Omega is a mock aggregate that contains all possible connections (due to A's sparsity pattern) to root ii Omega = find(A(ii,:)); % record index of root node rootIndex = find(Omega==ii); %solve constrained minimization problem Q = diag(D(Omega,:)); Bbar = B(Omega,:); ebar = e(Omega,:); zbar = z(Omega,:); q = Q(rootIndex,rootIndex); dd=size(ebar,2); ee=size(Bbar,2); blockA = [2*Bbar'*Q*Bbar q*Bbar'*ebar ;... %FIXME : missing Q(ii,ii) from 2,2 term ebar'* Bbar zeros(dd,ee) ]; blockRhs = [2*Bbar'*Q*zbar ; ... zbar(rootIndex)]; x = blockA \ blockRhs; ztilde = Bbar * x(1:end-1); %calculate SoC measure for each nonroot point in mock aggregate (each off-diagonal in row ii's stencil) WEAK=intmax; soc = zeros(size(Omega)); for kk=1:length(Omega) if ztilde(kk)/zbar(kk) < 0 soc(kk) = WEAK; else soc(kk) = abs( (zbar(kk) - ztilde(kk)) / zbar(kk) ); end end %find minimum over all nonroot points soc(rootIndex) = WEAK; minOverOmega = min(soc); %check SoC for each nonroot point nnz=length(Omega); for kk=1:length(Omega) S(ii,Omega(kk)) = soc(kk); if (soc(kk) > theta * minOverOmega) && (Omega(kk) ~= ii) %Omega(kk)'s connection to ii is weak, but never drop diagonal Graph.edges(ii,Omega(kk)) = false; numDropped = numDropped + 1; Filtering = true; nnz = nnz-1; else Graph.edges(ii,Omega(kk)) = true; end end S(ii,ii) = 1; if nnz == 1 Graph.boundaryNodes(end+1) = ii; end e(ii) = 0; deltaFn(ii) = 0; end %for ii=1:m fprintf('Evolution Soc: dropped %d connections\n', numDropped); fprintf('Evolution Soc: detected %d boundary nodes\n', length(Graph.boundaryNodes)); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
plotresults.m
.m
algebraic-distance-on-hypergraphs-master/packages/rol/example/PDE-OPT/0ld/adv-diff-react/plotresults.m
3,456
utf_8
f75d75d87da9229726780340d3183367
function plotresults adj = load('cell_to_node_quad.txt') + 1; %% load node adjacency table, increment by 1 for 1-based indexing nodes = load('nodes.txt'); %% load node coordinates publish_results = 0; axsize = 400; figure('Position', [100 100 3.3*axsize 1.6*axsize]) localplot('state.txt', 'control.txt', 'weights.txt', 'All sensors', adj, nodes, publish_results, axsize); if exist('weightsOED.txt', 'file') == 2 figure('Position', [150 150 3.3*axsize 1.6*axsize]) localplot('stateOED.txt', 'controlOED.txt', 'weightsOED.txt', 'OED sensors', adj, nodes, publish_results, axsize); end if exist('weightsRandom.txt', 'file') == 2 figure('Position', [200 200 3.3*axsize 1.6*axsize]) localplot('stateRandom.txt', 'controlRandom.txt', 'weightsRandom.txt', 'Random sensors', adj, nodes, publish_results, axsize); end end % plotresults function localplot(statefile, controlfile, weightsfile, weightscaption, adj, nodes, publish_results, axsize) subplot(2,3,4) data_obj = importdata('data.txt', ' ', 2); %% we need to skip the first two lines data = data_obj.data; trisurf(adj, nodes(:,1), nodes(:,2), data); shading interp; view(2); axis square; xlabel('x'); ylabel('y'); title('Data (true state)'); subplot(2,3,1) data_obj = importdata('sources.txt', ' ', 2); %% we need to skip the first two lines sources = data_obj.data; % normalize source data to 1 maxsource = max(abs(sources)); sources = sources * (1/maxsource); trisurf(adj, nodes(:,1), nodes(:,2), sources); shading interp; view(2); axis square; xlabel('x'); ylabel('y'); title('True sources'); subplot(2,3,5) data_obj = importdata(statefile, ' ', 2); %% we need to skip the first two lines state = data_obj.data; trisurf(adj, nodes(:,1), nodes(:,2), state); shading interp; view(2); axis square; xlabel('x'); ylabel('y'); title('Computed state'); subplot(2,3,2) data_obj = importdata(controlfile, ' ', 2); %% we need to skip the first two lines control = data_obj.data; trisurf(adj, nodes(:,1), nodes(:,2), control); shading interp; view(2); axis square; xlabel('x'); ylabel('y'); title('Computed sources'); subplot(2,3,3) trisurf(adj, nodes(:,1), nodes(:,2), sources-control); shading interp; view(2); axis square; xlabel('x'); ylabel('y'); title('Source error (rel)'); colorbar subplot(2,3,6) trisurf(adj, nodes(:,1), nodes(:,2), (state-data)/max(abs(data))); shading interp; view(2); axis square; xlabel('x'); ylabel('y'); title('State error (rel)'); colorbar set(findall(gcf,'-property','FontSize'),'FontSize',16); set(gcf, 'Color', 'White'); tightfig; if publish_results myaa(2); myaa('publish'); end fig1 = gcf; sizevec = get(fig1, 'Position'); figure('Position', [sizevec(1)+sizevec(3)+15 sizevec(2) axsize axsize]); data_obj = importdata('data.txt', ' ', 2); %% we need to skip the first two lines data = data_obj.data; trisurf(adj, nodes(:,1), nodes(:,2), data); shading interp; view(2); axis square; hold on; data_obj = importdata(weightsfile, ' ', 2); %% we need to skip the first two lines weights = data_obj.data; sum(weights) xloc = nodes(logical(weights),1); yloc = nodes(logical(weights),2); scatter3(xloc, yloc, 10*ones(size(xloc)), 22, 's', 'MarkerEdgeColor', 'black', 'MarkerFaceColor', 'white', 'LineWidth', 2); view(2); axis square; xlabel('x'); ylabel('y'); title(weightscaption); set(findall(gcf,'-property','FontSize'),'FontSize',16); set(gcf, 'Color', 'White'); tightfig; if publish_results myaa(2); myaa('publish'); end end % localplot
github
rsln-s/algebraic-distance-on-hypergraphs-master
VanderPol.m
.m
algebraic-distance-on-hypergraphs-master/packages/rythmos/test/VanderPol/VanderPol.m
895
utf_8
b4985ee0d3b112de000a0c5353665db0
% % Exact discrete solution to Van der Pol equation with Backward Euler % function [x0n1,x1n1] = VanderPol(N) format long e; % IC: x0n = 2.0; x1n = 0.0; x0n1 = [x0n]; % IC x1n1 = [x1n]; % IC epsilon = 0.5; h = 0.1; for i=[1:N] t = 0.0 + i*h; fn = forcing_term(t,epsilon); [x0n1_temp,x1n1_temp] = solveCubic(x0n,x1n,epsilon,h,fn); x0n1 = [x0n1,x0n1_temp]; x1n1 = [x1n1,x1n1_temp]; x0n = x0n1_temp; x1n = x1n1_temp; end; function [f] = forcing_term(t,epsilon) x0 = 2*cos(t)+epsilon*(0.75*sin(t)-0.25*sin(3*t)); x1 = -2*sin(t)+epsilon*(0.75*cos(t)-0.75*cos(3*t)); f = -2*cos(t)+epsilon*(-0.75*sin(t)+(9/4)*sin(3*t))-epsilon*(1-x0*x0)*x1+x0; function [x0n1,x1n1] = solveCubic(x0n,x1n,epsilon,h,fn) a3 = epsilon/h; a2 = -epsilon/h*x0n; a1 = 1/(h*h)+1-epsilon/h; a0 = epsilon/h*x0n-(1/(h*h))*x0n-(1/h)*x1n-fn; poly=[a3,a2,a1,a0]; R = roots(poly); x0n1 = R(3); x1n1 = (x0n1-x0n)/h;
github
rsln-s/algebraic-distance-on-hypergraphs-master
FE.m
.m
algebraic-distance-on-hypergraphs-master/packages/rythmos/test/complicatedExample/FE.m
295
utf_8
97e90972599f7096259e6d12d735e1b7
% % This is the exact output of Forward Euler applied to % \dot{x} - \Lambda x = 0 % x(0) = x0 % t = 0 .. 1 % with fixed step-sizes equal to 1/n. % % Example: % n = 4; % lambda = [-2:3/(n-1):1]'; % x0 = 10*ones(n,1); % FE(x0,lambda,n); % function xn = FE(x0,lambda,n) xn = x0.*(1+lambda/n).^n;
github
rsln-s/algebraic-distance-on-hypergraphs-master
BE.m
.m
algebraic-distance-on-hypergraphs-master/packages/rythmos/test/complicatedExample/BE.m
301
utf_8
5e7652c74c4ee4fb8b581bad9c6010af
% % This is the exact output of Backward Euler applied to % \dot{x} - \Lambda x = 0 % x(0) = x0 % t = 0 .. 1 % with fixed step-sizes equal to 1/n. % % Example: % n = 4; % lambda = [-2:3/(n-1):1]'; % x0 = 10*ones(n,1); % BE(x0,lambda,n); % function xn = BE(x0,lambda,n) xn = x0.*(1./(1-lambda/n)).^n;
github
rsln-s/algebraic-distance-on-hypergraphs-master
triangle_mesh_reader.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/mesh/triangle_mesh_reader.m
4,167
utf_8
0ab6701aa066ef2697a0796c4845daec
% % function [mesh] = triangle_mesh_reader( filename ) % % PURPOSE: Read mesh information from filename.node, filename.ele % and filename.edge files generated by the 2D mesh generator % TRIANGLE % % Input: % filename string containing the base of the filenames % generated by TRIANGLE. (This Matlab functtion % will read from filename.node, filename.ele % and filename.edge). % % Output: % mesh structure array with the following fields % % mesh.p Real np x 2 % array containing the x- and y- coordinates % of the nodes % % mesh.t Integer nt x 3 or nt x 6 % t(i,1:4) contains the indices of the vertices of % triangle i. % If t is a nt x 6 array, t(i,4:6) contains % the indices of the edge mid-points of triangle i. % % mesh.e Integer ne x 3 or ne x 4 % e(i,1:2) contains the indices of the vertices of % edge i. % If mesh.e is of size ne x 3, then % edge(i,3) contains the boundary marker of edge i. % e(i,3) = 1 Dirichlet bdry conds are imposed on edge i % e(i,3) = 2 Neumann bdry conds are imposed on edge i % e(i,3) = 3 Robin bdry conds are imposed on edge i % If mesh.e is of size ne x 4, then % e(i,3) contains the index of the midpoint of edge i. % e(i,4) contains the boundary marker % e(i,4) = 1 Dirichlet bdry conds are imposed on edge i % e(i,4) = 2 Neumann bdry conds are imposed on edge i % % AUTHOR: Denis Ridzal % Matthias Heinkenschloss % Department of Computational and Applied Mathematics % Rice University % November 23, 2005 % function [mesh] = triangle_mesh_reader( filename ) % open node file for reading fid = fopen( [ filename '.node'] ); % read first line (number of vertices) tmp = fscanf( fid, ' %d %d %d %d ', [1, 4]); nv = tmp(1); dim = tmp(2); nattrib = tmp(3); bdrymarker = tmp(4); % read node coorddinates (ignore attributes, i.e. assumed to be 0) if (nattrib==0) tmp = fscanf( fid, ' %d %f %f %d', [3+nattrib+bdrymarker,nv]); % discard numbering indices and boundary markers mesh.p = tmp(2:3,:)'; else fprintf('Vertices have additional attributes!\n'); fprintf('Modify triangle_mesh_reader.m accordingly.\n'); return; end fclose(fid); % open element file for reading fid = fopen( [ filename '.ele'] ); % read first line (number of vertices) tmp = fscanf( fid, ' %d %d %d ', [1, 3]); nt = tmp(1); nnodes = tmp(2); nattrib = tmp(3); % read node indices for triangle i (ignore attributes) if( nnodes == 3 ) tmp = fscanf( fid, ' %d %d %d %d ', [1+nnodes,nt]); end if( nnodes == 6 ) tmp = fscanf( fid, ' %d %d %d %d %d %d %d', [1+nnodes,nt]); end mesh.t = tmp(2:1+nnodes,:)'; fclose(fid); % open edge file for reading fid = fopen( [ filename '.edge'] ); % read first line (number of vertices) tmp = fscanf( fid, ' %d %d ', [1, 2]); ne = tmp(1); bdrymarker = tmp(2); % read node indices for edge i and boundary marker tmp = fscanf( fid, ' %d %d %d %d ', [4, ne]); fclose(fid); if( size(mesh.t,1) == 3 ) % get boundary edges only % (assume that all boundary edges have maker > 0!) mesh.e = tmp(2:4,:)'; mesh.e = mesh.e(mesh.e(:,3) > 0,:); else % get boundary edges only % (assume that all boundary edges have maker > 0!) ind = (tmp(4,:) > 0); ne = sum(ind); mesh.e = zeros(ne, 4); mesh.e(:,[1,2,4]) = tmp(2:4,ind)'; % determine mid points %%% Get the number of nodes and vertices. Mid points have indices %%% nv+1,...,nn nn = size(mesh.p,1); nv = max( max(mesh.t(:,1:3)) ); for i = 1:ne mid = ones(nn-nv,1)*( 0.5*(mesh.p(mesh.e(i,1),:)+mesh.p(mesh.e(i,2),:)) ); [x,k] = min( sum(abs(mesh.p(nv+1:nn,:)-mid),2) ); mesh.e(i,3) = nv+k; end end
github
rsln-s/algebraic-distance-on-hypergraphs-master
RectGridDD.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/mesh/RectGridDD.m
1,433
utf_8
92dfc8d69c5602c395b9164b5226d91e
function [mesh] = RectGridDD(nsdx, nsdy, t, p, e) % % AUTHOR: Matthias Heinkenschloss and Denis Ridzal % Department of Computational and Applied Mathematics % Rice University % November 23, 2005 xmin = min(p(:,1)); xmax = max(p(:,1)); ymin = min(p(:,2)); ymax = max(p(:,2)); elempart = zeros(size(t,1),1); for k = 1:size(t,1) x = p(t(k,:),1); % x coordinates of all vertives in triangle k y = p(t(k,:),2); % y coordinates of all vertives in triangle k isd = 0; % subdomain number for i = 1:nsdx for j = 1:nsdy isd = isd+1; if( all( x >= xmin+(i-1)*(xmax-xmin)/nsdx-1.e-10 ) ... & all( x <= xmin+i*(xmax-xmin)/nsdx+1.e-10 ) ... & all( y >= ymin+(j-1)*(ymax-ymin)/nsdy-1.e-10 ) ... & all( y <= ymin+j*(ymax-ymin)/nsdy+1.e-10 ) ) % all vertices of triangle k are inside subdomain k, % i.e. triangke k is inside subdomain k elempart(k) = isd-1; end end end end [mesh] = meshpart(t, p, e, elempart); % plot the partition color = ['w','r','g','b','c','m','y']; nc = length(color); if 0 hold on; axis('equal','tight'); for i = 1:size(t,1) % plot each element x = p(t(i,1:3),1); y = p(t(i,1:3),2); c = mod(elempart(i),nc) + 1; fill(x,y,color(c)); plot(x, y, '-k'); end hold off; end
github
rsln-s/algebraic-distance-on-hypergraphs-master
vel_pres_vtk2d.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/mesh/vel_pres_vtk2d.m
4,549
utf_8
ad3b298d72ef7e3456f5a158dbe893a1
% % vel_pres_vtk2d(vtkfile, xy, t, vel, pressure) % vel_pres_vtk2d(vtkfile, xy, t, vel, pressure, vort, stream) % % % INPUT: % vtkfile base name of file % vel_pres_vtk2d generates vtkfile_vel.vtu % and vel_pres_vtk2d_pres.vtu % % xy real nx x 2 % x-y-coordinates of the vertices in the triangulation. % xy(i,1) x-coordinate of node i, % xy(i,2) y-coordinate of node i. % % t real nt x 6 % indices of the vertices in a triangle % t(i,j) index of the j-th vertex in triangle i % % vel real nn x 2 % velocity at nodes % % pressure real nv x 1 % pressure at vertices % % vort real nn x 2 % vorticity at nodes [optional] % % stream real nn x 2 % streamfunction at nodes [optional] % % % AUTHOR: Denis Ridzal and Matthias Heinkenschloss % Department of Computational and Applied Mathematics % Rice University % Novemer 15, 2005 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = vel_pres_vtk2d(vtkfile, xy, t, vel, pressure, varargin) % Write pressures % open file filename = [vtkfile,'_pres.vtk']; fid = fopen(filename,'w'); % write header fprintf(fid, '%s\n', '# vtk DataFile Version 3.0'); fprintf(fid, '%s\n', 'created by vel_pres_vtk2d.m'); fprintf(fid, '%s\n', 'ASCII'); fprintf(fid, '%s\n\n', 'DATASET UNSTRUCTURED_GRID'); nv = max(max(t(:,1:3))); % number of vertices, assumes that vertices % are first in xy, followed by mid points % (true for meshes generated by triangle fprintf(fid, '%s%d%s\n', 'POINTS ', nv, ' double'); for i = 1:nv fprintf(fid, '%13.6e %13.6e %13.6e \n', xy(i,:), 0); end fprintf(fid, '\n'); fprintf(fid, '%s %d %d\n', 'CELLS ', size(t,1), 4*size(t,1)); for i = 1:size(t,1) fprintf(fid, '%d %d %d %d \n', 3, t(i,1:3)-1); end fprintf(fid, '\n'); fprintf(fid, '%s %d \n', 'CELL_TYPES ', size(t,1)); for i = 1:size(t,1) fprintf(fid, '%d \n', 5); end fprintf(fid, '\n'); fprintf(fid, '%s %d \n', 'POINT_DATA ', nv); fprintf(fid, '%s \n', 'SCALARS pressure double 1'); fprintf(fid, '%s \n', 'LOOKUP_TABLE default'); for i = 1:nv fprintf(fid, '%13.6e \n', pressure(i)); end fprintf(fid, '%s \n', 'VECTORS velocities double'); for i = 1:nv fprintf(fid, '%13.6e %13.6e %13.6e\n', vel(i,:), 0); end fclose(fid); fprintf('... pressure data written to %s \n', filename) % Write velocities % open file filename = [vtkfile,'_vel.vtk']; fid = fopen(filename,'w'); % write header fprintf(fid, '%s\n', '# vtk DataFile Version 3.0'); fprintf(fid, '%s\n', 'created by vel_pres_vtk2d.m'); fprintf(fid, '%s\n', 'ASCII'); fprintf(fid, '%s\n\n', 'DATASET UNSTRUCTURED_GRID'); fprintf(fid, '%s%d%s\n', 'POINTS ', size(xy,1), ' double'); for i = 1:size(xy,1) fprintf(fid, '%13.6e %13.6e %13.6e \n', xy(i,:), 0); end fprintf(fid, '\n'); fprintf(fid, '%s %d %d\n', 'CELLS ', 4*size(t,1), 16*size(t,1)); for i = 1:size(t,1) fprintf(fid, '%d %d %d %d \n', 3, t(i,[1,6,5])-1); fprintf(fid, '%d %d %d %d \n', 3, t(i,[4,5,6])-1); fprintf(fid, '%d %d %d %d \n', 3, t(i,[2,4,6])-1); fprintf(fid, '%d %d %d %d \n', 3, t(i,[5,4,3])-1); end fprintf(fid, '\n'); fprintf(fid, '%s %d \n', 'CELL_TYPES ', 4*size(t,1)); for i = 1:4*size(t,1) fprintf(fid, '%d \n', 5); end fprintf(fid, '\n'); fprintf(fid, '%s %d \n', 'POINT_DATA ', size(xy,1)); if( nargin > 5 ) vort = varargin{1}; stream = varargin{2}; fprintf(fid, '%s \n', 'SCALARS vorticity double 1'); fprintf(fid, '%s \n', 'LOOKUP_TABLE default'); for i = 1:size(xy,1) fprintf(fid, '%13.6e \n', vort(i)); end fprintf(fid, '\n'); fprintf(fid, '%s \n', 'SCALARS stream_fucntion double 1'); fprintf(fid, '%s \n', 'LOOKUP_TABLE default'); for i = 1:size(xy,1) fprintf(fid, '%13.6e \n', stream(i)); end end fprintf(fid, '\n'); fprintf(fid, '%s \n', 'VECTORS velocities double'); for i = 1:size(xy,1) fprintf(fid, '%13.6e %13.6e %13.6e\n', vel(i,:), 0); end % close file fclose(fid); if( nargin > 5 ) fprintf('... velocity, vorticity and streamfunction data written to %s \n', filename); else fprintf('... velocity data written to %s \n', filename); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
RectGridQuad.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/mesh/RectGridQuad.m
4,792
utf_8
c3becc3dffb4abbbd715c48ac19c1e76
function [mesh] = RectGridQuad(xmin, xmax, ymin, ymax, nx, ny) % % [mesh] = RectGridQuad(xmin, xmax, ymin, ymax, nx, ny) % %RECTGRID sets up the grid for piecewise linear elements % in a rectangular domain on quadrilateral cells. % % The grid is constructed by subdividing the x-interval into % nx subintervals and the y-interval into ny subintervals. % This generates a grid with nx*ny rectangular quadrilaterals. % % % % Input % xmin, xmax size of the rectangle % ymin, ymax % nx number of subintervals on x-interval % ny number of subintervals on y-interval % % Output % mesh structure array with the following fields % % mesh.p Real num_nodes x 2 % array containing the x- and y- coordinates % of the nodes % % mesh.t Integer num_cells x 4 % t(i,1:4) contains the indices of the vertices of % quadrilateral i. % % mesh.e Integer num_edges x 3 % e(i,1:2) contains the indices of the vertices of % edge i. % edge(i,3) contains the boundary marker of edge i. % Currently set to one. % e(i,3) = 1 Dirichlet bdry conds are imposed on edge i % e(i,3) = 2 Neumann bdry conds are imposed on edge i % e(i,3) = 3 Robin bdry conds are imposed on edge i % % mesh.sidesPerCell Integer = 4 (Quadrilateral) % % mesh.elem_ss{i} = global element IDs on sideset (boundary) i % % mesh.side_ss{i} = local side (subcell) IDs on sideset (boundary) i % % mesh.cellType = string for cell type (= 'Quadrilateral') % % mesh.sideType = string for side subcell type (= 'Line') % % % Vertical ordering: % The quadrilaterals are ordered column wise, for instance: % % 03 -------- 06 -------- 09 -------- 12 % | | | | % | 2 | 4 | 6 | % | | | | % 02 -------- 05 -------- 08 -------- 11 % | | | | % | 1 | 3 | 5 | % | | | | % 01 -------- 04 -------- 07 -------- 10 % % The vertices in a quadrilateral are numbered % counterclockwise, for example % quadrilateral 3: (04, 07, 08, 05) % quadrilateral 6: (08, 11, 12, 09) % % (Usually, the local grid.node numbering should not be important.) % % number of quadrilaterals: nx*ny, % number of vertices: (nx+1)*(ny+1), % % AUTHOR: % Denis Ridzal % Sandia National Laboratories nt = nx*ny; np = (nx+1)*(ny+1); % Create arrays mesh.t = zeros(nt,4); mesh.p = zeros(np,2); nxp1 = nx + 1; nyp1 = ny + 1; % Create quadrilaterals nt = 0; for ix = 1:nx for iy = 1:ny iv = (ix-1)*nyp1 + iy; iv1 = iv + nyp1; nt = nt + 1; mesh.t(nt,1) = iv; mesh.t(nt,2) = iv1; mesh.t(nt,3) = iv1+1; mesh.t(nt,4) = iv+1; end end % Create vertex coodinates hx = (xmax-xmin)/nx; hy = (ymax-ymin)/ny; x = xmin; for ix = 1:nx % set coordinates for vertices with fixed % x-coordinate at x i1 = (ix-1)*(ny+1)+1; i2 = ix*(ny+1); mesh.p(i1:i2,1) = x*ones(nyp1,1); mesh.p(i1:i2,2) = (ymin:hy:ymax)'; x = x + hx; end % set coordinates for vertices with fixed % x-coordinate at xmax i1 = nx*(ny+1)+1; i2 = (nx+1)*(ny+1); mesh.p(i1:i2,1) = xmax*ones(nyp1,1); mesh.p(i1:i2,2) = (ymin:hy:ymax)'; % Set grid.edge (edges are numbered counter clock wise starting % at lower left end). mesh.e = ones(2*(nx+ny),3); % edges on left on left boundary mesh.e(1:ny,1) = (1:ny)'; mesh.e(1:ny,2) = (2:ny+1)'; % edges on top boundary mesh.e(ny+1:nx+ny,1) = (ny+1:ny+1:np-1)'; mesh.e(ny+1:nx+ny,2) = (2*(ny+1):ny+1:np)'; % edges on right boundary mesh.e(nx+ny+1:nx+2*ny,1) = (np-ny:np-1)'; mesh.e(nx+ny+1:nx+2*ny,2) = (np-ny+1:np)'; % edges on lower boundary mesh.e(nx+2*ny+1:2*(nx+ny),1) = (1:ny+1:np-2*ny-1)'; mesh.e(nx+2*ny+1:2*(nx+ny),2) = (ny+2:ny+1:np-ny)'; % sides per cell mesh.sidesPerCell = 4; % cell type mesh.cellType = 'Quadrilateral'; % side type mesh.sideType = 'Line'; % sidesets xvec = [1:nx]'; yvec = [1:ny]'; mesh.elem_ss{1} = ny*(xvec-1) + 1; % bottom mesh.elem_ss{2} = ny*(nx-1) + (yvec-1) + 1; % right mesh.elem_ss{3} = ny*xvec; % top mesh.elem_ss{4} = yvec; % left % local side ids for sidesets mesh.side_ss{1} = 0*ones(nx,1); % bottom mesh.side_ss{2} = 1*ones(ny,1); % right mesh.side_ss{3} = 2*ones(nx,1); % top mesh.side_ss{4} = 3*ones(ny,1); % left
github
rsln-s/algebraic-distance-on-hypergraphs-master
RectGridTri.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/mesh/RectGridTri.m
5,059
utf_8
c0bad327e12ce727266b74a28a5cfd88
function [mesh] = RectGrid(xmin, xmax, ymin, ymax, nx, ny) % % [mesh] = RectGrid(xmin, xmax, ymin, ymax, nx, ny) % %RECTGRID sets up the grid for piecewise linear elements % in a rectangular domain. % % The grid is constructed by subdividing the x-interval into % nx subintervals and the y-interval into ny subintervals. % This generates a grid with nx*ny rectangles. Each rectangle % is then subdivided into two triangles by cutting the rectangle % from bottom left to top right. % % % % Input % xmin, xmax size of the rectangle % ymin, ymax % nx number of subintervals on x-interval % ny number of subintervals on y-interval % % Output % mesh structure array with the following fields % % mesh.p Real nn x 2 % array containing the x- and y- coordinates % of the nodes % % mesh.t Integer nt x 3 % t(i,1:4) contains the indices of the vertices of % triangle i. % % mesh.e Integer nf x 3 % e(i,1:2) contains the indices of the vertices of % edge i. % edge(i,3) contains the boundary marker of edge i. % Currently set to one. % e(i,3) = 1 Dirichlet bdry conds are imposed on edge i % e(i,3) = 2 Neumann bdry conds are imposed on edge i % e(i,3) = 3 Robin bdry conds are imposed on edge i % % mesh.sidesPerCell Integer = 3 (triangle) % % mesh.elem_ss{i} = global element IDs on sideset (boundary) i % % mesh.side_ss{i} = local side (subcell) IDs on sideset (boundary) i % % mesh.cellType = string for cell type (= 'Triangle') % % mesh.sideType = string for side subcell type (= 'Line') % % % Vertical ordering: % The triangles are ordered column wise, for instance: % % 03 -------- 06 -------- 09 -------- 12 % | 4 / | 8 / | 12 / | % | / | / | / | % | / 3 | / 7 | / 11 | % 02 -------- 05 -------- 08 -------- 11 % | 2 / | 6 / | 10 / | % | / | / | / | % | / 1 | / 5 | / 9 | % 01 -------- 04 -------- 07 -------- 10 % % The vertices and midpoints in a triangle are numbered % counterclockwise, for example % triangle 7: (05, 08, 09) % triangle 8: (05, 09, 06) % % (Usually, the local grid.node numbering should not be important.) % % number of triangles: 2*nx*ny, % number of vertices: (nx+1)*(ny+1), % % AUTHORS: Matthias Heinkenschloss and Denis Ridzal % Department of Computational and Applied Mathematics % Rice University % November 23, 2005 % % Denis Ridzal % Sandia National Laboratories nt = 2*nx*ny; np = (nx+1)*(ny+1); % Create arrays mesh.t = zeros(nt,3); mesh.p = zeros(np,2); nxp1 = nx + 1; nyp1 = ny + 1; % Create triangles nt = 0; for ix = 1:nx for iy = 1:ny iv = (ix-1)*nyp1 + iy; iv1 = iv + nyp1; nt = nt + 1; mesh.t(nt,1) = iv; mesh.t(nt,2) = iv1; mesh.t(nt,3) = iv1+1; nt = nt+1; mesh.t(nt,1) = iv; mesh.t(nt,2) = iv1+1; mesh.t(nt,3) = iv+1; end end % Create vertex coodinates hx = (xmax-xmin)/nx; hy = (ymax-ymin)/ny; x = xmin; for ix = 1:nx % set coordinates for vertices with fixed % x-coordinate at x i1 = (ix-1)*(ny+1)+1; i2 = ix*(ny+1); mesh.p(i1:i2,1) = x*ones(nyp1,1); mesh.p(i1:i2,2) = (ymin:hy:ymax)'; x = x + hx; end % set coordinates for vertices with fixed % x-coordinate at xmax i1 = nx*(ny+1)+1; i2 = (nx+1)*(ny+1); mesh.p(i1:i2,1) = xmax*ones(nyp1,1); mesh.p(i1:i2,2) = (ymin:hy:ymax)'; % Set grid.edge (edges are numbered counter clock wise starting % at lower left end). mesh.e = ones(2*(nx+ny),3); % edges on left on left boundary mesh.e(1:ny,1) = (1:ny)'; mesh.e(1:ny,2) = (2:ny+1)'; % edges on top boundary mesh.e(ny+1:nx+ny,1) = (ny+1:ny+1:np-1)'; mesh.e(ny+1:nx+ny,2) = (2*(ny+1):ny+1:np)'; % edges on right boundary mesh.e(nx+ny+1:nx+2*ny,1) = (np-ny:np-1)'; mesh.e(nx+ny+1:nx+2*ny,2) = (np-ny+1:np)'; % edges on lower boundary mesh.e(nx+2*ny+1:2*(nx+ny),1) = (1:ny+1:np-2*ny-1)'; mesh.e(nx+2*ny+1:2*(nx+ny),2) = (ny+2:ny+1:np-ny)'; % sides per cell mesh.sidesPerCell = 3; % cell type mesh.cellType = 'Triangle'; % side type mesh.sideType = 'Line'; % sidesets xvec = [1:nx]'; yvec = [1:ny]'; mesh.elem_ss{1} = 2*ny*(xvec-1) + 1; % bottom mesh.elem_ss{2} = 2*ny*(nx-1) + 2*(yvec-1) + 1; % right mesh.elem_ss{3} = 2*ny*xvec; % top mesh.elem_ss{4} = 2*yvec; % left % local side ids for sidesets mesh.side_ss{1} = 0*ones(nx,1); % bottom mesh.side_ss{2} = 1*ones(ny,1); % right mesh.side_ss{3} = 1*ones(nx,1); % top mesh.side_ss{4} = 2*ones(ny,1); % left
github
rsln-s/algebraic-distance-on-hypergraphs-master
reg_mesh_refine2_mid.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/mesh/reg_mesh_refine2_mid.m
9,000
utf_8
3103a9464b4bf6af260b31619fc9799e
function [mesh1, I1] = reg_mesh_refine2_mid(mesh) %FIX THE COMMENTS LATER % [mesh1,I1]=reg_mesh_refine2(mesh) % % Compute a regular refinement of a mesh given by p, e, t. % Each triangle of the original mesh is refined into four triangles % by dividing each edge into two. % % Input % mesh structure with the fields mesh.p, mesh.e, mesh.t % If size(mesh.t, 2) == 3 % mesh.p(i, 1:2) x-, y-coordinates of the i-th vertex % % mesh.e(i, 1:2) indices of vertices of boundary edge i. % mesh.e(i, 3) boundary marker of edge i % % mesh.t(i, 1:3) indices of vertices in triangle i. % If size(mesh.t, 2) == 6 % mesh.p(i, 1:2) x-, y-coordinates of the i-th vertex % % mesh.e(i, 1:2) indices of vertices of boundary edge i. % mesh.e(i, 3) indices of the mid-point of boundary edge i. % mesh.e(i, 4) boundary marker of edge i % % mesh.t(i, 1:3) indices of vertices in triangle i. % mesh.t(i, 4:6) indices of mid-points in triangle i. % % Output % mesh1 structure with the fields mesh1.p, mesh1.e, mesh1.t % If size(mesh.t, 2) == 3 % mesh1.p(i, 1:2) x-, y-coordinates of the i-th vertex in % the refined mesh. % If np = size(mesh.p, 1), then mesh1.p(1:np, :) = mesh.p. % % mesh1.e(i, 1:2) indices of vertices of boundary edge i of % the refined mesh % mesh1.e(i, 3) boundary marker of edge i of the refined mesh. % If ne = size(mesh.e, 1), then mesh1.e(1:ne, :) = mesh.e. % % mesh1.t(i, 1:3) indices of vertices in triangle i of the % refined mesh. % If nt = size(mesh.t, 1), then mesh1.t(1:nt, :) = mesh.t. % If size(mesh.t, 2) == 6 % mesh1.p(i, 1:2) x-, y-coordinates of the i-th vertex in % the refined mesh. % If np = size(mesh.p, 1), then mesh1.p(1:np, :) = mesh.p. % % mesh1.e(i, 1:2) indices of vertices of boundary edge i of % the refined mesh % mesh1.e(i, 3) indices of mid-point of boundary edge i of % the refined mesh % mesh1.e(i, 4) boundary marker of edge i of the refined % mesh. % % mesh1.t(i, 1:3) indices of vertices in triangle i of the % refined mesh. % mesh1.t(i, 4:6) indices of mid-points in triangle i of the % refined mesh. % % I1 Interpolation matrix of size np1 x np, where np1 is the number % of vertices in the refined mesh and np is the number of % vertices in the original mesh. % If u is the vector of function values of a piecewise linear function % on the original mesh (u(i) is the function value at node % mesh.p(i,:)), then u1 = I1*u is the vector of function values of the % piecewise linear function on the refined mesh (u1(i) is the function % value at node mesh1.p(i,:)). % % reg_mesh_refine2_mid is based on a modification of refinemesh.m in the Matlab PDEToolbox. % % AUTHOR: Patricia A. Howard % Department of Computational and Applied Mathematics % Rice University % March 3, 2006 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % np = size(mesh.p, 1); nt = 0; ne = 0; % Cannot use matrix indices that exceeds the size of a signed int [comp, maxsize] = computer; indexproblem = np^2 > maxsize; % Make a connectivity matrix, with edges to be refined. % -1 means no point is yet allocated it = []; ip1 = []; ip2 = []; ip3 = []; ip4 = []; ip5 = []; ip6 = []; if size(mesh.t, 2) == 3 ne = size(mesh.e, 1); nt = size(mesh.t, 1); it =(1:nt); ip1 = mesh.t(it, 1); ip2 = mesh.t(it, 2); ip3 = mesh.t(it, 3); elseif size(mesh.t, 2) == 6 ip1 = mesh.t(:, 1); ip2 = mesh.t(:, 2); ip3 = mesh.t(:, 3); ip4 = mesh.t(:, 4); ip5 = mesh.t(:, 5); ip6 = mesh.t(:, 6); % Construct new triangles with existing mid-point information mesh1.t = [ip1 ip6 ip5; ip2 ip4 ip6; ip4 ip5 ip6; ip3 ip5 ip4]; nt = size(mesh1.t, 1); it =(1:nt); ip1 = mesh1.t(it, 1); ip2 = mesh1.t(it, 2); ip3 = mesh1.t(it, 3); ne = 2 * size(mesh.e, 1); % Construct new edges with existing mid-point information mesh1.e = [mesh.e(:, 1) mesh.e(:, 3) (-1 * ones(length(mesh.e(:, 1)), 1)) mesh.e(:, 4); mesh.e(:, 3) mesh.e(:, 2) (-1 * ones(length(mesh.e(:, 2)), 1)) mesh.e(:, 4)]; end A = sparse(ip1, ip2, -1, np, np); A = A + sparse(ip2, ip3, -1, np, np); A = A + sparse(ip3, ip1, -1, np, np); A = -((A + A.') < 0); % Generate points on (interior and boundary) edges % Determine (interior and boundary) edges [i1, i2] = find(A == -1 & A.' == -1); i = find(i2 > i1); i1 = i1(i); i2 = i2(i); % Edges (interior and boundary) have vertices i1 i2. % Compute midpoints mesh1.p = [mesh.p; ((mesh.p(i1,1:2) + mesh.p(i2,1:2))/2)]; % Fill in the new points. % The midpoint of edge with vertices i1 and i2 gets index ip ip = ((np + 1):(np + length(i)))'; if ~indexproblem A(i1 + np * (i2 - 1)) = ip; A(i2 + np * (i1 - 1)) = ip; else A=l_assign(A, [i1 i2], [i2 i1], [ip ip]); end % Construct interpolation matrix I1 = []; if size(mesh.t, 2) == 3 irowI1 = [(1:np)']; icolI1 = [(1:np)']; sI1 = [ones(np, 1)]; irowI1 = [irowI1; ip; ip]; icolI1 = [icolI1; i1; i2]; sI1 = [sI1; 0.5 * ones(2 * length(i), 1)]; I1 = sparse(irowI1, icolI1, sI1); elseif size(mesh.t, 2) == 6 % Constructs an interpolation matrix for linear elements % WITHOUT mid-point (as is required in source-inv) nv = max(max(mesh.t(:, 1:3))); row_col_val = [(1:nv)' (1:nv)' ones(nv, 1)]; row_col_val = [row_col_val; ip6 mesh.t(:, 1) 0.5 * ones(length(ip6), 1); ip6 mesh.t(:, 2) 0.5 * ones(length(ip6), 1); ip4 mesh.t(:, 2) 0.5 * ones(length(ip4), 1); ip4 mesh.t(:, 3) 0.5 * ones(length(ip4), 1); ip5 mesh.t(:, 3) 0.5 * ones(length(ip5), 1); ip6 mesh.t(:, 1) 0.5 * ones(length(ip5), 1)]; row_col_val = unique(row_col_val, 'rows'); I1 = sparse(row_col_val(:, 1), row_col_val(:, 2), row_col_val(:, 3)); end % Form the new triangles (if size(mesh.t, 2) = 3) or % new mid-points (if size(mesh.t, 2) = 6) if ~indexproblem mp1 = full(A(ip2 + np * (ip3 - 1))); % mp1 is index of midpoint of edge opposite of vectex 1 mp2 = full(A(ip3 + np * (ip1 - 1))); % mp2 is index of midpoint of edge opposite of vectex 2 mp3 = full(A(ip1 + np * (ip2 - 1))); % mp3 is index of midpoint of edge opposite of vectex 3 else mp1 = l_extract(A, ip2, ip3); mp2 = l_extract(A, ip3, ip1); mp3 = l_extract(A, ip1, ip2); end if size(mesh.t, 2) == 3 mesh1.t = zeros(4 * nt, 3); i = (1:nt); nt1 = 0; mesh1.t((nt1 + 1):(nt1 + length(i)), :)=[mesh.t(it(i), 1) mp3(i) mp2(i)]; nt1 = nt1 + length(i); mesh1.t((nt1 + 1):(nt1 + length(i)), :) = [mesh.t(it(i), 2) mp1(i) mp3(i)]; nt1 = nt1 + length(i); mesh1.t((nt1 + 1):(nt1 + length(i)), :) = [mesh.t(it(i), 3) mp2(i) mp1(i)]; nt1 = nt1 + length(i); mesh1.t((nt1 + 1):(nt1 + length(i)), :) = [mp1(i) mp2(i) mp3(i)]; nt1 = nt1 + length(i); elseif size(mesh.t, 2) == 6 i = (1:nt); mesh1.t(it, 4) = mp1(i); mesh1.t(it, 5) = mp2(i); mesh1.t(it, 6) = mp3(i); end % Form new edges (if size(mesh.t, 2) = 3) or add mid-points (if % size(mesh.t, 2) = 6) ie = (1:ne); if size(mesh.t, 2) == 3 if ~indexproblem mp1 = full(A(mesh.e(ie, 1) + np * (mesh.e(ie, 2) - 1))); %mp1 is index of midpoint of edge ie else mp1 = l_extract(A, mesh.e(ie, 1), mesh.e(ie, 2)); end % Create new edges mesh1.e = [[mesh.e(ie,1) mp1 mesh.e(ie,3)]; ... [mp1 mesh.e(ie,2) mesh.e(ie,3)]]; elseif size(mesh.t, 2) == 6 if ~indexproblem mp1 = full(A(mesh1.e(ie, 1) + np * (mesh1.e(ie, 2) - 1))); %mp1 is index of midpoint of edge ie else mp1 = l_extract(A, mesh1.e(ie, 1), mesh1.e(ie, 2)); end mesh1.e(:, 3) = mp1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function k=l_extract(A,i,j) if numel(i)~=numel(j) error('PDE:refinemesh:ijNumel', 'i and j must have the same number of elements.') end k=zeros(size(i)); for l=1:numel(i) k(l)=A(i(l),j(l)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function A=l_assign(A,i,j,k) if numel(i)~=numel(j) || numel(i)~=numel(k) error('PDE:refinemesh:ijkNumel', 'i, j, and k must have the same number of elements.') end for l=1:numel(i) A(i(l),j(l))=k(l); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
reg_mesh_refine2.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/mesh/reg_mesh_refine2.m
5,027
utf_8
69c7e3f6eb32f842d2afe5cc3b6cf3cf
function [mesh1,I1]=reg_mesh_refine2(mesh) % % [mesh1,I1]=reg_mesh_refine2(mesh) % % Compute a regular refinement of a mesh given by p, e, t. % Each triangle of the original mesh is refined into four triangles % by dividing each edge into two. % % Input % mesh structure with the fields mesh.p, mesh.e, mesh.t % mesh.p(i,1:2) x-, y-coordinates of the i-th vertex % % mesh.e(i,1:2) indices of vertices of boundary edge i. % mesh.e(i,3) boundary marker of edge i % % mesh.t(i,1:3) indices of vertices in triangle i. % % Output % mesh1 structure with the fields mesh1.p, mesh1.e, mesh1.t % mesh1.p(i,1:2) x-, y-coordinates of the i-th vertex in % the refined mesh. % If np = size(mesh.p,1), then mesh1.p(1:np,:) = mesh.p. % % mesh1.e(i,1:2) indices of vertices of boundary edge i of % the refined mesh % mesh1.e(i,3) boundary marker of edge i of the refined mesh. % If ne = size(mesh.e,1), then mesh1.e(1:ne,:) = mesh.e. % % mesh1.t(i,1:3) indices of vertices in triangle i of the % refined mesh. % If nt = size(mesh.t,1), then mesh1.t(1:nt,:) = mesh.t. % % I1 Interpolation matrix of size np1 x np, where np1 is the number % of nodes in the refined mesh and np is the number of nodes % in the original mesh. % If u is the vector of function values of a piecewise linear function % on the original mesh (u(i) is the function value at node % mesh.p(i,:)), then u1 = I1*u is the vector of function values of the % piecewise linear function on the refined mesh (u1(i) is the function % value at node mesh1.p(i,:)). % % reg_mesh_refine2 is based on a modification of refinemesh.m in the Matlab PDEToolbox. % % AUTHOR: Matthias Heinkenschloss and Denis Ridzal % Department of Computational and Applied Mathematics % Rice University % December 1, 2005 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % np=size(mesh.p,1); ne=size(mesh.e,1); nt=size(mesh.t,1); % Cannot use matrix indices that exceeds the size of a signed int [comp,maxsize]=computer; indexproblem=np^2>maxsize; % Make a connectivity matrix, with edges to be refined. % -1 means no point is yet allocated it =(1:nt); ip1=mesh.t(it,1); ip2=mesh.t(it,2); ip3=mesh.t(it,3); A=sparse(ip1,ip2,-1,np,np); A=A+sparse(ip2,ip3,-1,np,np); A=A+sparse(ip3,ip1,-1,np,np); A=-((A+A.')<0); % Generate points on (interior and boundary) edges % Determine (interior and boundary) edges [i1,i2]=find(A==-1 & A.'==-1); i=find(i2>i1); i1=i1(i); i2=i2(i); % Edges (interior and boundary) have vertices i1 i2. % Compute midpoints mesh1.p=[mesh.p; ((mesh.p(i1,1:2)+mesh.p(i2,1:2))/2)]; % Fill in the new points. % The midpoint of edge with vertices i1 and i2 gets index ip ip=((np+1):(np+length(i)))'; if ~indexproblem A(i1+np*(i2-1))=ip; A(i2+np*(i1-1))=ip; else A=l_assign(A,[i1 i2],[i2 i1],[ip ip]); end % interpolation matrix irowI1 = [(1:np)']; icolI1 = [(1:np)']; sI1 = [ones(np,1)]; irowI1 = [irowI1; ip; ip]; icolI1 = [icolI1; i1; i2]; sI1 = [sI1; 0.5*ones(2*length(i),1)]; I1 = sparse(irowI1,icolI1,sI1); % Form the new triangles ip1=mesh.t(it,1); ip2=mesh.t(it,2); ip3=mesh.t(it,3); if ~indexproblem mp1=full(A(ip2+np*(ip3-1))); %mp1 is index of midpoint of edge opposite of vectex 1 mp2=full(A(ip3+np*(ip1-1))); %mp2 is index of midpoint of edge opposite of vectex 2 mp3=full(A(ip1+np*(ip2-1))); %mp3 is index of midpoint of edge opposite of vectex 3 else mp1=l_extract(A,ip2,ip3); mp2=l_extract(A,ip3,ip1); mp3=l_extract(A,ip1,ip2); end mesh1.t =zeros(4*nt,3); i = (1:nt); nt1=0; mesh1.t((nt1+1):(nt1+length(i)),:)=[mesh.t(it(i),1) mp3(i) mp2(i)]; nt1=nt1+length(i); mesh1.t((nt1+1):(nt1+length(i)),:)=[mesh.t(it(i),2) mp1(i) mp3(i)]; nt1=nt1+length(i); mesh1.t((nt1+1):(nt1+length(i)),:)=[mesh.t(it(i),3) mp2(i) mp1(i)]; nt1=nt1+length(i); mesh1.t((nt1+1):(nt1+length(i)),:)=[mp1(i) mp2(i) mp3(i)]; nt1=nt1+length(i); % form new edges ie = (1:ne); if ~indexproblem mp1=full(A(mesh.e(ie,1)+np*(mesh.e(ie,2)-1))); %mp1 is index of midpoint of edge ie else mp1=l_extract(A,mesh.e(ie,1),mesh.e(ie,2)); end % Create new edges mesh1.e=[[mesh.e(ie,1) mp1 mesh.e(ie,3)]; ... [mp1 mesh.e(ie,2) mesh.e(ie,3)]]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function k=l_extract(A,i,j) if numel(i)~=numel(j) error('PDE:refinemesh:ijNumel', 'i and j must have the same number of elements.') end k=zeros(size(i)); for l=1:numel(i) k(l)=A(i(l),j(l)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function A=l_assign(A,i,j,k) if numel(i)~=numel(j) || numel(i)~=numel(k) error('PDE:refinemesh:ijkNumel', 'i, j, and k must have the same number of elements.') end for l=1:numel(i) A(i(l),j(l))=k(l); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
build_elastic_rbm.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/src/build_elastic_rbm.m
1,224
utf_8
0c478367726c0666fea83faeb72d1718
%function [RBM, NDOF]=build_elastic_rbm(NODES) % Given a set of nodes in 1, 2 or 3 dimensions construct the % rigid-body modes for the (elastic) structure % by: Chris Siefert % Modified by Denis Ridzal on 10/24/2012: % - fixed performance issue with sparse vs. zeros % - returned dimension and number of rigid body modes % function [RBM, dim, numRBM]=build_elastic_rbm(NODES) % Constants [N,dim]=size(NODES); NDOF=[1,3,6]; numRBM=NDOF(dim); % Allocs %RBM=sparse(dim*N,numRBM); RBM=zeros(dim*N,numRBM); % Translational DOFs / INDICES for I=1:dim, IDX{I}=I:dim:dim*N; RBM(IDX{I},I)=ones(N,1); end % Recenter nodes CTR=sum(NODES) / N; CNODES = NODES - repmat(CTR,N,1); % Rotational DOF: Thanks to Farhat, Pierson and Lesoinne 2000, % equation (52), you know, once I've managed to make sense out of % the blasted thing. if(dim>=2) % Rotate in X-Y Plane (around Z axis): [-y ;x]; RBM(IDX{1},dim+1)=-CNODES(:,2); RBM(IDX{2},dim+1)= CNODES(:,1); end if(dim==3) % Rotate in Y-Z Plane (around X axis): [-z;y] RBM(IDX{2},dim+2)=-CNODES(:,3); RBM(IDX{3},dim+2)= CNODES(:,2); % Rotate in X-Z Plane (around Y axis): [z ;-x] RBM(IDX{1},dim+3)= CNODES(:,3); RBM(IDX{3},dim+3)=-CNODES(:,1); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
basicTest.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/test/basic/basicTest.m
372
utf_8
f667342dacdfdc2a756f854c8483aff0
function tests = basicTest tests = functiontests(localfunctions); end function testIntrepid(testCase) act_fdiff = m2i_test; exp_fdiff = 0; verifyEqual(testCase,act_fdiff,exp_fdiff,'AbsTol',1e-8); end function testIntrepidAndML(testCase) act_solnorm = m2ml_test; exp_solnorm = 2.5888736e+03; verifyEqual(testCase,act_solnorm,exp_solnorm,'RelTol',1e-6); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
dofmaps.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/test/poisson_fem/dofmaps.m
2,528
utf_8
81a4cce4a72b169ea56b53ef1caba4f7
% function [cellNodes, iIdx, jIdx, iVecIdx] = dofmaps(mesh, nVert, numCells) % % PURPOSE: Given a mesh in point/triangle/edge format, generate % degree-of-freedom maps compatible with Intrepid. % % INPUT: mesh structure array with the following fields % % - mesh.p Real nn x 2 % array containing the x- and y- % coordinates of the nodes % % % - mesh.t Integer nt x 3 % t(i,1:4) contains the indices of the % vertices of triangle i. % % - mesh.e Integer nf x 3 % e(i,1:2) contains the indices of the % vertices of edge i. % edge(i,3) contains the boundary marker % of edge i. % Currently set to one. % e(i,3) = 1 Dirichlet bdry conds are % imposed on edge i % e(i,3) = 2 Neumann bdry conds are % imposed on edge i % e(i,3) = 3 Robin bdry conds are % imposed on edge i % % nVert number of cell vertices % % numCells number of working cells % % OUTPUT: cellNodes Integer 3 x numCells % contains all the indices of the vertices % of cell i. % % iIdx % % jIdx % % iVecIdx % function [cellNodes, iIdx, jIdx, iVecIdx] = dofmaps(mesh, nVert, numCells) iIdx_tmp = zeros(3*size(mesh.t,1),size(mesh.t,2)); jIdx_tmp = zeros(size(mesh.t,1),3*size(mesh.t,2)); for i=1:nVert iIdx_tmp(i:nVert:numel(mesh.t),:) = mesh.t; for j=1:nVert jIdx_tmp(:, (i-1)*nVert+j) = mesh.t(:,i); end end iIdx = reshape(iIdx_tmp', 1, numel(iIdx_tmp)); jIdx = reshape(jIdx_tmp', 1, numel(jIdx_tmp), 1); clear iIdx_tmp; clear jIdx_tmp; % get rhs array index iVecIdx = reshape(mesh.t',1,numel(mesh.t)); cellNodesAll = mesh.p(mesh.t',:)'; % format to match Intrepid cellNodes = reshape(cellNodesAll, 2, nVert, numCells); clear cellNodesAll; end
github
rsln-s/algebraic-distance-on-hypergraphs-master
poissonTest.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/test/poisson_fem/poissonTest.m
212
utf_8
bfb7ce34e64fc9f1a545f1f45f4a8027
function tests = poissonTest tests = functiontests(localfunctions); end function testConvergence(testCase) act_rate = conv_test; exp_rate = 1.9; verifyGreaterThanOrEqual(testCase,act_rate,exp_rate); end
github
rsln-s/algebraic-distance-on-hypergraphs-master
conv_test.m
.m
algebraic-distance-on-hypergraphs-master/packages/intrepid/matlab/intrelab/test/poisson_fem/conv_test.m
4,513
utf_8
593863c7fb1ef86b1390cf94f23909b3
% Convergence test for Poisson problem. function rate = conv_test clear all; set(0, 'defaultaxesfontsize',12,'defaultaxeslinewidth',0.7,... 'defaultlinelinewidth',0.8,'defaultpatchlinewidth',0.7,... 'defaulttextfontsize',12); % mesh utilities directory addpath ../../mesh/ % choose solution plotting iplot = 0; fprintf('\nTesting mesh convergence of Poisson solver ...\n'); % set rhs_fn = @rhs_sine; rhs_fn=@(usr_par)rhs_sine(usr_par); % set diff_fn = @diff_const; diff_fn=@(usr_par)diff_const(usr_par); usr_par = []; gridsizes = [4:9]; L2_err = []; for imesh = gridsizes clear usr_par; % number of intervals in x and y direction on a rectangular grid nxint = 2^imesh; nyint = nxint; % set up PDE fprintf('\nSetting up problem and assembling FEM operators ...\n'); tic [usr_par] = problemsetup(nxint, nyint, rhs_fn, diff_fn); toc % solve PDE fprintf('\nSolving PDE ...\n\n'); tic [u] = pdesolve(usr_par); toc if iplot figure(1) trisurf(usr_par.mesh.t, usr_par.mesh.p(:,1), usr_par.mesh.p(:,2), ... u, 'facecolor','interp') view(0,90); axis equal axis tight shading interp; title('PDE Solution') xlabel('x') ylabel('y') pause(1) end %%% Compute error: % set up more accurate numerical integration cubDegree = 6; numCubPoints = intrepid_getNumCubaturePoints(usr_par.cellType, cubDegree); cubPoints = zeros(usr_par.spaceDim, numCubPoints); cubWeights = zeros(1, numCubPoints); intrepid_getCubature(cubPoints, cubWeights, usr_par.cellType, cubDegree); val_at_cub_points = zeros(numCubPoints, usr_par.numFields); intrepid_getBasisValues(val_at_cub_points, cubPoints, 'OPERATOR_VALUE', usr_par.cellType, 1); transformed_val_at_cub_points = zeros(numCubPoints, usr_par.numFields, usr_par.numCells); intrepid_HGRADtransformVALUE(transformed_val_at_cub_points, val_at_cub_points); cellMeasures = zeros(numCubPoints, usr_par.numCells); cellJacobians = zeros(usr_par.spaceDim, usr_par.spaceDim, numCubPoints, usr_par.numCells); cellJacobianInvs = zeros(usr_par.spaceDim, usr_par.spaceDim, numCubPoints, usr_par.numCells); cellJacobianDets = zeros(numCubPoints, usr_par.numCells); intrepid_setJacobian(cellJacobians, cubPoints, usr_par.cellNodes, usr_par.cellType); intrepid_setJacobianInv(cellJacobianInvs, cellJacobians); intrepid_setJacobianDet(cellJacobianDets, cellJacobians); intrepid_computeCellMeasure(cellMeasures, cellJacobianDets, cubWeights); % evaluate approximate solution at integration points approxSolnCoeffs = reshape(u(usr_par.iVecIdx), usr_par.numFields, usr_par.numCells); % scatter to cells approxSolnValues = zeros(numCubPoints, usr_par.numCells); intrepid_evaluate(approxSolnValues, ... approxSolnCoeffs, ... transformed_val_at_cub_points); % evaluate true solution at integration points % (first map reference integration points to physical frame) cubPointsPhysCoords = zeros(usr_par.spaceDim,numCubPoints,usr_par.numCells); intrepid_mapToPhysicalFrame(cubPointsPhysCoords, ... cubPoints, ... usr_par.cellNodes, ... usr_par.cellType); trueSolnValues = zeros(numCubPoints, usr_par.numCells); trueSolnValues = soln_sine(cubPointsPhysCoords); % evaluate difference diffSolnValues = trueSolnValues-approxSolnValues; % evaluate measure-weighted difference diffSolnValuesWeighted = zeros(numCubPoints, usr_par.numCells); intrepid_scalarMultiplyDataData(diffSolnValuesWeighted, cellMeasures, diffSolnValues); % compute L2 error err = zeros(1,usr_par.numCells); intrepid_integrate(err, diffSolnValues, ... diffSolnValuesWeighted, 'COMP_BLAS'); L2_err = [L2_err sqrt(sum(err))]; end L2_ratio = [0 L2_err(1:end-1)]./L2_err; L2_rate = 0; L2_rate_c = 0; for i=2:length(L2_err) p = polyfit(log(1./(2.^gridsizes(i-1:i))), log(L2_err(i-1:i)), 1); L2_rate = [L2_rate p(1)]; end for i=2:length(L2_err) p = polyfit(log(1./(2.^gridsizes(1:i))), log(L2_err(1:i)), 1); L2_rate_c = [L2_rate_c p(1)]; end fprintf('\n mesh L2 error ratio rate_two_grid rate_cummulative\n'); fprintf(' %04dx%04d %6.2e %6.2e %6.2e %6.2e\n', [2.^gridsizes; 2.^gridsizes; L2_err; L2_ratio; L2_rate; L2_rate_c]); rate = L2_rate(end); fprintf('\nDone testing mesh convergence of Poisson solver.\n\n'); end % function conv_test
github
rsln-s/algebraic-distance-on-hypergraphs-master
zoltPartSpy.m
.m
algebraic-distance-on-hypergraphs-master/packages/zoltan/src/matlab/zoltPartSpy.m
5,538
utf_8
25b420e3bee7272a09ff3bdb9ae16c74
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This matlab function produces spy-like plots in which the nonzeros are % colored based on the partition that owns them. % % The function takes 3 arguments: the filename of a matrix in matrix market % format, the name of the zoltan output file containg partition info, and % the type of partitioning ('1DRow', '1DColumn', '1.5DRow', '1.5DColumn'). % % Written by Michael Wolf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function partSpyZoltan(matFilename,partFilename,partType) if nargin ~= 3 error('Wrong number of input arguments. \n %s', ... 'Usage: partSpyZoltan mtxFile partitionFile PartitionType') end % Parse zdrive output file, Erik Boman's code fp = fopen(partFilename, 'r'); if (~fp) error('Could not open partition file\n'); end % Skip all lines before 'GID' word = 'abc'; while (~strncmp(word, 'GID', 3)) % Read only first word, ignore rest of line word = fscanf(fp,'%s',1); fscanf(fp,'%*[^\n]',1); end % Read the partition numbers; file has 4 fields per line [P, num] = fscanf(fp, '%d', [4,inf]); % First two rows in P (columns in output file) give the partition vector part = zeros(size(P(1,:))); part(P(1,:)) = P(2,:); if strcmp(partType, '1DColumn') partSpyZolt1DC(matFilename,part); elseif strcmp(partType, '1DRow') partSpyZolt1DR(matFilename,part); elseif strcmp(partType, '1.5DColumn') partSpyZolt1_5DC(matFilename,part); elseif strcmp(partType, '1.5DRow') partSpyZolt1_5DR(matFilename,part); else error('Unsupported partitioning scheme ''%s''',partType); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for zoltan with stripped partition information % 1d column partitioning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function partSpyZolt1DC(matFilename,part) A = mmread(matFilename); numParts=max( part ) +1; numParts for i=1:numParts [colors(i,:),symbols(i)]=plotcolors(i,numParts); x{i}=[]; y{i}=[]; end [i,j,val] = find(A); n=length(i); for cnt=1:n x{part(j(cnt))+1}(end+1) = j(cnt); y{part(j(cnt))+1}(end+1) = i(cnt); end figure; hold on; for cnt=1:numParts plot(x{cnt},y{cnt}, symbols(cnt), 'Color', colors(cnt,:), ... 'MarkerSize', 6); end view([0 0 -1]) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for zoltan with stripped partition information % 1d row partitioning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function partSpyZolt1DR(matFilename,part) A = mmread(matFilename); numParts=max( part ) +1; numParts for i=1:numParts [colors(i,:),symbols(i)]=plotcolors(i,numParts); x{i}=[]; y{i}=[]; end [i,j,val] = find(A); n=length(i); for cnt=1:n x{part(i(cnt))+1}(end+1) = j(cnt); y{part(i(cnt))+1}(end+1) = i(cnt); end figure; hold on; for cnt=1:numParts plot(x{cnt},y{cnt}, symbols(cnt), 'Color', colors(cnt,:), ... 'MarkerSize', 6); end view([0 0 -1]) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for zoltan with stripped partition information % 1.5d col partitioning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function partSpyZolt1_5DC(matFilename,part) A = mmread(matFilename); numParts=max( part ) +1; numParts for i=1:numParts [colors(i,:),symbols(i)]=plotcolors(i,numParts); x{i}=[]; y{i}=[]; end [i,j,val] = find(A); n=length(i); for cnt=1:n if i(cnt) >= j(cnt) x{part(j(cnt))+1}(end+1) = j(cnt); y{part(j(cnt))+1}(end+1) = i(cnt); else x{part(i(cnt))+1}(end+1) = j(cnt); y{part(i(cnt))+1}(end+1) = i(cnt); end end figure; hold on; for cnt=1:numParts plot(x{cnt},y{cnt}, symbols(cnt), 'Color', colors(cnt,:), ... 'MarkerSize', 6); end view([0 0 -1]) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for zoltan with stripped partition information % 1.5d row partitioning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function partSpyZolt1_5DR(matFilename,part) A = mmread(matFilename); numParts=max( part ) +1; numParts for i=1:numParts [colors(i,:),symbols(i)]=plotcolors(i,numParts); x{i}=[]; y{i}=[]; end [i,j,val] = find(A); n=length(i); for cnt=1:n if i(cnt) >= j(cnt) x{part(i(cnt))+1}(end+1) = j(cnt); y{part(i(cnt))+1}(end+1) = i(cnt); else x{part(j(cnt))+1}(end+1) = j(cnt); y{part(j(cnt))+1}(end+1) = i(cnt); end end figure; hold on; for cnt=1:numParts plot(x{cnt},y{cnt}, symbols(cnt), 'Color', colors(cnt,:), ... 'MarkerSize', 6); end view([0 0 -1]) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
rsln-s/algebraic-distance-on-hypergraphs-master
plotcolors.m
.m
algebraic-distance-on-hypergraphs-master/packages/zoltan/src/matlab/plotcolors.m
1,481
utf_8
dc7cd5753308a48fd7b6e77b2c9b0c03
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This matlab function returns a unique color/symbol pair for plotting. % The total number of color/symbol pairs needed and the index of this % color/symbol are taken as input arguments. % % Written by Michael Wolf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [colorV,symb] = plotcolors(cindex,numcolors) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% For 4 or fewer colors if numcolors <= 4 switch cindex case 1 colorV = [1 0 0]; case 2 colorV = [0 1 0]; case 3 colorV = [0 0 1]; otherwise colorV = [0 1 1]; end symb = '.'; %% For colors else % cmap = lines(numcolors); % cmap = hsv(numcolors); %% ten distinct colors, add more later diffColors=8; cmap(1,:) = [ 1 0 0]; % red cmap(2,:) = [ 0 1 0]; % green cmap(3,:) = [ 0 0 1]; % blue cmap(4,:) = [ 0 1 1]; % cyan cmap(5,:) = [ 1 0 1]; % magenta cmap(6,:) = [ 0 0 0]; % black cmap(7,:) = [ 1 0.67 0]; % orange cmap(8,:) = [ 0.6 0.6 0.6]; % gray % cmap(9,:) = [0.75 0.75 0]; % dark yellow % cmap(10,:) = [ 0 0.4 0]; % dark green colorV = cmap(mod(cindex-1,diffColors)+1,:); if floor((cindex-1)/diffColors) == 0 symb = '.'; else symb = 'o'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end
github
soichih/app-conn-preprocessing-master
preprocess.m
.m
app-conn-preprocessing-master/preprocess.m
6,024
utf_8
b9b5bfd25d2d73636e34ef1c81fea5ae
% batch processing script derived from the CONN toolbox script (conn_batch_workshop_nyudataset.m; https://sites.google.com/view/conn/resources/source) for the NYU_CSC_TestRetest dataset (published in Shehzad et al., 2009, The Resting Brain: Unconstrained yet Reliable. Cerebral Cortex. doi:10.1093/cercor/bhn256) % % Lorenzo Pasquini PhD, November 2017 % [email protected], % Memory and Aging Center UCSF % % Steps: % 1. Run conn_batch_workshop_nyudataset. The script will: % % a) Preprocessing of the anatomical and functional volumes % (normalization & segmentation of anatomical volumes; realignment, % coregistration, normalization, outlier detection, and smooting of the % functional volumes) % b) Estimate first-level seed-to-voxel connectivity maps for each of % the default seeds (located in the conn/rois folder), separately % for each subject and for each of the three test-retest sessions. % function [] = preprocess() clear all; clc; %doesn't revent all dialog prompt but... set(0,'DefaultFigureVisible','off'); % load my own config.json config = loadjson('config.json') %% FIND functional/structural files cwd=pwd; FUNCTIONAL_FILE=cellstr(conn_dir(config.bold)); %UI STRUCTURAL_FILE=cellstr(conn_dir(config.t1)); %UI nsubjects=1; if rem(length(FUNCTIONAL_FILE),nsubjects),error('mismatch number of functionalfiles'); end if rem(length(STRUCTURAL_FILE),nsubjects),error('mismatch number of anatomical files'); end nsessions=length(FUNCTIONAL_FILE)/nsubjects; FUNCTIONAL_FILE=reshape(FUNCTIONAL_FILE,[nsubjects,nsessions]); STRUCTURAL_FILE={STRUCTURAL_FILE{1:nsubjects}}; disp([num2str(size(FUNCTIONAL_FILE,1)),' subjects']); disp([num2str(size(FUNCTIONAL_FILE,2)),' sessions']); %% CONN-SPECIFIC SECTION: RUNS PREPROCESSING/SETUP/DENOISING/ANALYSIS STEPS %% Prepares batch structure clear batch; batch.filename=fullfile(cwd,'output.mat'); %% SETUP & PREPROCESSING step (using default values for most parameters, see help conn_batch to define non-default values) % CONN Setup % Default options (uses all ROIs in conn/rois/ directory); see conn_batch for additional options % CONN Setup.preprocessing (realignment/coregistration/segmentation/normalization/smoothing) batch.Setup.isnew=1; batch.Setup.nsubjects=1; batch.Setup.RT=config.tr; % UI TR (seconds) batch.Setup.functionals=repmat({{}},[1,1]); % Point to functional volumes for each subject/session for nsub=1:1, for nses=1:nsessions, batch.Setup.functionals{nsub}{nses}{1}=FUNCTIONAL_FILE{nsub,nses}; end end %note: each subject's data is defined by three sessions and one single (4d) file per session batch.Setup.structurals=STRUCTURAL_FILE; % Point to anatomical volumes for each subject nconditions=nsessions; % treats each session as a different condition (comment the following three lines and lines 84-86 below if you do not wish to analyze between-session differences) if nconditions==1 batch.Setup.conditions.names={'rest'}; for ncond=1,for nsub=1:1,for nses=1:nsessions, batch.Setup.conditions.onsets{ncond}{nsub}{nses}=0; batch.Setup.conditions.durations{ncond}{nsub}{nses}=inf;end;end;end % rest condition (all sessions) else batch.Setup.conditions.names=[{'rest'}, arrayfun(@(n)sprintf('Session%d',n),1:nconditions,'uni',0)]; for ncond=1,for nsub=1:1,for nses=1:nsessions, batch.Setup.conditions.onsets{ncond}{nsub}{nses}=0; batch.Setup.conditions.durations{ncond}{nsub}{nses}=inf;end;end;end % rest condition (all sessions) for ncond=1:nconditions,for nsub=1:1,for nses=1:nsessions, batch.Setup.conditions.onsets{1+ncond}{nsub}{nses}=[];batch.Setup.conditions.durations{1+ncond}{nsub}{nses}=[]; end;end;end for ncond=1:nconditions,for nsub=1:1,for nses=ncond, batch.Setup.conditions.onsets{1+ncond}{nsub}{nses}=0; batch.Setup.conditions.durations{1+ncond}{nsub}{nses}=inf;end;end;end % session-specific conditions end batch.Setup.preprocessing.steps=config.steps; batch.Setup.preprocessing.sliceorder=config.sliceorder; batch.Setup.preprocessing.fwhm=config.fwhm; % UI, smoothing kernel batch.Setup.preprocessing.art_thresholds=[5,0.9]; % outlier detector, set to default batch.Setup.outputfiles=[0,1,0]; % writing of denoised data as nifti batch.Setup.done=1; batch.Setup.overwrite='Yes'; % uncomment the following 3 lines if you prefer to run one step at a time: % conn_batch(batch); % runs Preprocessing and Setup steps only % clear batch; % batch.filename=fullfile(cwd,'conn_NYU.mat'); % Existing conn_*.mat experiment name %% DENOISING step % CONN Denoising % Default options (uses White Matter+CSF+realignment+scrubbing+conditions as confound regressors); see conn_batch for additional options for thispart = 1 if config.do_global_signal_regression batch.Denoising.confounds.names={'Grey Matter','White Matter','CSF','realignment','scrubbing','Effect of rest'}; else batch.Denoising.confounds.names={'White Matter','CSF','realignment','scrubbing','Effect of rest'}; end end batch.Denoising.filter=[config.filter_bandpass_min, config.filter_bandpass_max]; % UI, frequency filter (band-pass values, in Hz) batch.Denoising.done=1; batch.Denoising.overwrite='Yes'; % uncomment the following 3 lines if you prefer to run one step at a time: % conn_batch(batch); % runs Denoising step only % clear batch; % batch.filename=fullfile(cwd,'conn_NYU.mat'); % Existing conn_*.mat experiment name %% FIRST-LEVEL ANALYSIS step % CONN Analysis % Default options (uses all ROIs in conn/rois/ as connectivity sources); see conn_batch for additional options batch.Analysis.done=1; batch.Analysis.overwrite='Yes'; %% Run all analyses conn_batch(batch); quit
github
durgeshsamariya/Coursera_MachineLearning_Course-master
submit.m
.m
Coursera_MachineLearning_Course-master/Week 2/machine-learning-ex1/ex1/submit.m
1,876
utf_8
8d1c467b830a89c187c05b121cb8fbfd
function submit() addpath('./lib'); conf.assignmentSlug = 'linear-regression'; conf.itemName = 'Linear Regression with Multiple Variables'; conf.partArrays = { ... { ... '1', ... { 'warmUpExercise.m' }, ... 'Warm-up Exercise', ... }, ... { ... '2', ... { 'computeCost.m' }, ... 'Computing Cost (for One Variable)', ... }, ... { ... '3', ... { 'gradientDescent.m' }, ... 'Gradient Descent (for One Variable)', ... }, ... { ... '4', ... { 'featureNormalize.m' }, ... 'Feature Normalization', ... }, ... { ... '5', ... { 'computeCostMulti.m' }, ... 'Computing Cost (for Multiple Variables)', ... }, ... { ... '6', ... { 'gradientDescentMulti.m' }, ... 'Gradient Descent (for Multiple Variables)', ... }, ... { ... '7', ... { 'normalEqn.m' }, ... 'Normal Equations', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId) % Random Test Cases X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))']; Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2)); X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25]; Y2 = Y1.^0.5 + Y1; if partId == '1' out = sprintf('%0.5f ', warmUpExercise()); elseif partId == '2' out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]')); elseif partId == '3' out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10)); elseif partId == '4' out = sprintf('%0.5f ', featureNormalize(X2(:,2:4))); elseif partId == '5' out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]')); elseif partId == '6' out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10)); elseif partId == '7' out = sprintf('%0.5f ', normalEqn(X2, Y2)); end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
submitWithConfiguration.m
.m
Coursera_MachineLearning_Course-master/Week 2/machine-learning-ex1/ex1/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
savejson.m
.m
Coursera_MachineLearning_Course-master/Week 2/machine-learning-ex1/ex1/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
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: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % 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). % 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.NoRowBracket [1|0]: 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.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, 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'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(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 if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.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{:}); 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; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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); 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)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- 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) ||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('NoRowBracket',1,varargin{:})==1 && 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('NoRowBracket',1,varargin{:})==1) 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=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 else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
loadjson.m
.m
Coursera_MachineLearning_Course-master/Week 2/machine-learning-ex1/ex1/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
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: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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, 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,'[\{\}\]\[]','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{:}); 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(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end 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{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- 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=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=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 && ndims(object)==2) 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 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 = 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 len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = 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 true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end 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
durgeshsamariya/Coursera_MachineLearning_Course-master
loadubjson.m
.m
Coursera_MachineLearning_Course-master/Week 2/machine-learning-ex1/ex1/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
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: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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. % % 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, 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 if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end 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 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); 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 isoct 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 && ndims(object)==2) 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 = parseStr(varargin) global pos inStr esc index_esc len_esc % 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 len 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 len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end 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
durgeshsamariya/Coursera_MachineLearning_Course-master
saveubjson.m
.m
Coursera_MachineLearning_Course-master/Week 2/machine-learning-ex1/ex1/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
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: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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) % 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.NoRowBracket [1|0]: 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.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, 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'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(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 if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.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{:}); 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 len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(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>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) 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); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) 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) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) 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=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(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) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_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('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(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,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; 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(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); 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=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
durgeshsamariya/Coursera_MachineLearning_Course-master
submit.m
.m
Coursera_MachineLearning_Course-master/Week 6/machine-learning-ex5/ex5/submit.m
1,765
utf_8
b1804fe5854d9744dca981d250eda251
function submit() addpath('./lib'); conf.assignmentSlug = 'regularized-linear-regression-and-bias-variance'; conf.itemName = 'Regularized Linear Regression and Bias/Variance'; conf.partArrays = { ... { ... '1', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Cost Function', ... }, ... { ... '2', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Gradient', ... }, ... { ... '3', ... { 'learningCurve.m' }, ... 'Learning Curve', ... }, ... { ... '4', ... { 'polyFeatures.m' }, ... 'Polynomial Feature Mapping', ... }, ... { ... '5', ... { 'validationCurve.m' }, ... 'Validation Curve', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)']; y = sin(1:3:30)'; Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)']; yval = sin(1:10)'; if partId == '1' [J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', J); elseif partId == '2' [J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', grad); elseif partId == '3' [error_train, error_val] = ... learningCurve(X, y, Xval, yval, 1); out = sprintf('%0.5f ', [error_train(:); error_val(:)]); elseif partId == '4' [X_poly] = polyFeatures(X(2,:)', 8); out = sprintf('%0.5f ', X_poly); elseif partId == '5' [lambda_vec, error_train, error_val] = ... validationCurve(X, y, Xval, yval); out = sprintf('%0.5f ', ... [lambda_vec(:); error_train(:); error_val(:)]); end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
submitWithConfiguration.m
.m
Coursera_MachineLearning_Course-master/Week 6/machine-learning-ex5/ex5/lib/submitWithConfiguration.m
5,569
utf_8
cc10d7a55178eb991c495a2b638947fd
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); partss = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, partss); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(partss, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submission_Url = submissionUrl(); responseBody = getResponse(submission_Url, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submission_Url = submissionUrl() submission_Url = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
savejson.m
.m
Coursera_MachineLearning_Course-master/Week 6/machine-learning-ex5/ex5/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
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: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % 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). % 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.NoRowBracket [1|0]: 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.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, 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'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(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 if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.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{:}); 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; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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); 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)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- 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) ||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('NoRowBracket',1,varargin{:})==1 && 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('NoRowBracket',1,varargin{:})==1) 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=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 else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
loadjson.m
.m
Coursera_MachineLearning_Course-master/Week 6/machine-learning-ex5/ex5/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
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: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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, 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,'[\{\}\]\[]','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{:}); 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(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end 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{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- 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=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=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 && ndims(object)==2) 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 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 = 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 len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = 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 true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end 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
durgeshsamariya/Coursera_MachineLearning_Course-master
loadubjson.m
.m
Coursera_MachineLearning_Course-master/Week 6/machine-learning-ex5/ex5/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
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: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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. % % 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, 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 if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end 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 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); 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 isoct 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 && ndims(object)==2) 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 = parseStr(varargin) global pos inStr esc index_esc len_esc % 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 len 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 len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end 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
durgeshsamariya/Coursera_MachineLearning_Course-master
saveubjson.m
.m
Coursera_MachineLearning_Course-master/Week 6/machine-learning-ex5/ex5/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
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: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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) % 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.NoRowBracket [1|0]: 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.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, 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'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(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 if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.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{:}); 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 len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(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>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) 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); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) 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) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) 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=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(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) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_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('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(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,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; 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(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); 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=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
durgeshsamariya/Coursera_MachineLearning_Course-master
submit.m
.m
Coursera_MachineLearning_Course-master/Week 8/machine-learning-ex7/ex7/submit.m
1,438
utf_8
665ea5906aad3ccfd94e33a40c58e2ce
function submit() addpath('./lib'); conf.assignmentSlug = 'k-means-clustering-and-pca'; conf.itemName = 'K-Means Clustering and PCA'; conf.partArrays = { ... { ... '1', ... { 'findClosestCentroids.m' }, ... 'Find Closest Centroids (k-Means)', ... }, ... { ... '2', ... { 'computeCentroids.m' }, ... 'Compute Centroid Means (k-Means)', ... }, ... { ... '3', ... { 'pca.m' }, ... 'PCA', ... }, ... { ... '4', ... { 'projectData.m' }, ... 'Project Data (PCA)', ... }, ... { ... '5', ... { 'recoverData.m' }, ... 'Recover Data (PCA)', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = reshape(sin(1:165), 15, 11); Z = reshape(cos(1:121), 11, 11); C = Z(1:5, :); idx = (1 + mod(1:15, 3))'; if partId == '1' idx = findClosestCentroids(X, C); out = sprintf('%0.5f ', idx(:)); elseif partId == '2' centroids = computeCentroids(X, idx, 3); out = sprintf('%0.5f ', centroids(:)); elseif partId == '3' [U, S] = pca(X); out = sprintf('%0.5f ', abs([U(:); S(:)])); elseif partId == '4' X_proj = projectData(X, Z, 5); out = sprintf('%0.5f ', X_proj(:)); elseif partId == '5' X_rec = recoverData(X(:,1:5), Z, 5); out = sprintf('%0.5f ', X_rec(:)); end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
submitWithConfiguration.m
.m
Coursera_MachineLearning_Course-master/Week 8/machine-learning-ex7/ex7/lib/submitWithConfiguration.m
5,569
utf_8
cc10d7a55178eb991c495a2b638947fd
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); partss = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, partss); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(partss, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submission_Url = submissionUrl(); responseBody = getResponse(submission_Url, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submission_Url = submissionUrl() submission_Url = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
savejson.m
.m
Coursera_MachineLearning_Course-master/Week 8/machine-learning-ex7/ex7/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
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: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % 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). % 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.NoRowBracket [1|0]: 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.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, 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'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(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 if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.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{:}); 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; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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); 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)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- 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) ||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('NoRowBracket',1,varargin{:})==1 && 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('NoRowBracket',1,varargin{:})==1) 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=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 else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
loadjson.m
.m
Coursera_MachineLearning_Course-master/Week 8/machine-learning-ex7/ex7/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
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: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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, 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,'[\{\}\]\[]','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{:}); 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(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end 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{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- 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=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=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 && ndims(object)==2) 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 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 = 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 len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = 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 true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end 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
durgeshsamariya/Coursera_MachineLearning_Course-master
loadubjson.m
.m
Coursera_MachineLearning_Course-master/Week 8/machine-learning-ex7/ex7/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
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: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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. % % 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, 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 if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end 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 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); 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 isoct 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 && ndims(object)==2) 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 = parseStr(varargin) global pos inStr esc index_esc len_esc % 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 len 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 len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end 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
durgeshsamariya/Coursera_MachineLearning_Course-master
saveubjson.m
.m
Coursera_MachineLearning_Course-master/Week 8/machine-learning-ex7/ex7/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
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: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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) % 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.NoRowBracket [1|0]: 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.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, 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'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(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 if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.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{:}); 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 len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(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>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) 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); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) 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) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) 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=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(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) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_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('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(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,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; 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(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); 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=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
durgeshsamariya/Coursera_MachineLearning_Course-master
submit.m
.m
Coursera_MachineLearning_Course-master/Week 5/machine-learning-ex4/ex4/submit.m
1,635
utf_8
ae9c236c78f9b5b09db8fbc2052990fc
function submit() addpath('./lib'); conf.assignmentSlug = 'neural-network-learning'; conf.itemName = 'Neural Networks Learning'; conf.partArrays = { ... { ... '1', ... { 'nnCostFunction.m' }, ... 'Feedforward and Cost Function', ... }, ... { ... '2', ... { 'nnCostFunction.m' }, ... 'Regularized Cost Function', ... }, ... { ... '3', ... { 'sigmoidGradient.m' }, ... 'Sigmoid Gradient', ... }, ... { ... '4', ... { 'nnCostFunction.m' }, ... 'Neural Network Gradient (Backpropagation)', ... }, ... { ... '5', ... { 'nnCostFunction.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = reshape(3 * sin(1:1:30), 3, 10); Xm = reshape(sin(1:32), 16, 2) / 5; ym = 1 + mod(1:16,4)'; t1 = sin(reshape(1:2:24, 4, 3)); t2 = cos(reshape(1:2:40, 4, 5)); t = [t1(:) ; t2(:)]; if partId == '1' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); elseif partId == '2' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); elseif partId == '3' out = sprintf('%0.5f ', sigmoidGradient(X)); elseif partId == '4' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; elseif partId == '5' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
submitWithConfiguration.m
.m
Coursera_MachineLearning_Course-master/Week 5/machine-learning-ex4/ex4/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
savejson.m
.m
Coursera_MachineLearning_Course-master/Week 5/machine-learning-ex4/ex4/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
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: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % 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). % 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.NoRowBracket [1|0]: 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.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, 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'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(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 if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.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{:}); 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; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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); 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)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- 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=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- 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) ||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('NoRowBracket',1,varargin{:})==1 && 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('NoRowBracket',1,varargin{:})==1) 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=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 else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
durgeshsamariya/Coursera_MachineLearning_Course-master
loadjson.m
.m
Coursera_MachineLearning_Course-master/Week 5/machine-learning-ex4/ex4/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
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: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % 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, 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,'[\{\}\]\[]','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{:}); 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(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end 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{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- 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=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=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 && ndims(object)==2) 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 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 = 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 len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = 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 true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end 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