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 | jiangyc92/LPPLModel-master | Train.m | .m | LPPLModel-master/@LPPL/Train.m | 1,478 | utf_8 | 2dd7765bf753ce5cac8fb67fe9324762 | function Train(obj, Times, Prices, t0)
% Train function solve the optimization problem and get the optimal
% paramater
% obj: class instantce
% Times: time sequence ( suggested to be 1:N)
% Prices: prices list
% t0: the start point for the optimization
ObjFunc = @(t) Func2(t, Times, log(Prices));
OptimProblem = createOptimProblem('fmincon','objective',ObjFunc,'lb',max(Times), ...
'x0',t0,'options',optimset('Display', 'iter'));
[tmin, Fmin] = fmincon(OptimProblem);
obj.tc = tmin;
[~, Para] = Func2(obj.tc, Times, log(Prices));
obj.m = Para.m;
obj.omega = Para.omega;
[~, Para] = Func1(tmin, obj.m, obj.omega, Times, log(Prices));
obj.A = Para.A;
obj.B = Para.B;
obj.C1 = Para.C1;
obj.C2 = Para.C2;
obj.TrainRes = Fmin;
end
function [Value, Para] = Func2(t, Times, LogPrices)
ObjSubFunc = @(x)Func1(t, x(1), x(2), Times, LogPrices);
OptimSubProblem = createOptimProblem('fmincon','objective',ObjSubFunc,...
'lb',[0,0],'ub',[1,Inf],...
'x0',[0.5,2],'options',optimset('Display','off'));
[Xmin,Fmin] = fmincon(OptimSubProblem);
Para.m = Xmin(1);
Para.omega = Xmin(2);
Value = Fmin;
end
function [Value, Para] = Func1(t, m, omega, Times, LogPrices)
dt = t - Times;
N = length(dt);
X = zeros(N,4);
X(:,1) = 1.0;
X(:,2) = dt.^m;
X(:,3) = (dt.^m) .* cos(omega*log(dt));
X(:,4) = (dt.^m) .* sin(omega*log(dt));
Coef = regress(LogPrices, X);
Para.A = Coef(1);
Para.B = Coef(2);
Para.C1 = Coef(3);
Para.C2 = Coef(4);
Value = sum((LogPrices - X*Coef).^2);
end
|
github | arvind96/Quantum-Mechanics-Simulations-master | ParticleInBoxWave.m | .m | Quantum-Mechanics-Simulations-master/ParticleInBoxWave.m | 365 | utf_8 | 172edcaf04f357dfbd97d910285f59be | function [z] = ParticleInBoxWave(L, c1, c2, c3, x, t)
z = c1 * (2/L)^0.5 *sin(1*pi*x / L) * exp(-1i*CalculateEnergy(1, L)*t / 1) + c2 * (2/L)^0.5 *sin(2*pi*x / L) * exp(-1i*CalculateEnergy(2, L)*t / 1) + c3 * (2/L)^0.5 *sin(3*pi*x / L) * exp(-1i*CalculateEnergy(3, L)*t / 1);
end
function e = CalculateEnergy(n, L)
e = (n^2 * pi^2 * 1) / (2 * 1 * L^2);
end |
github | arvind96/Quantum-Mechanics-Simulations-master | StartHydrogenAtomProbabilityDensity.m | .m | Quantum-Mechanics-Simulations-master/StartHydrogenAtomProbabilityDensity.m | 13,878 | utf_8 | c8e23f45fdd7a45863bd79212f7c1dfe | function StartHydrogenAtomProbabilityDensity()
global HydrogenOrbitalGenerationRunning;
if(HydrogenOrbitalGenerationRunning == 1)
return;
end
HydrogenOrbitalGenerationRunning = 1;
global MainHandle; %stores the handle for MainGUI
set(MainHandle.uipanelTopControls, 'Title', 'HYDROGEN ATOM');
set(MainHandle.uipanelOther1, 'Visible', 'On');
set(MainHandle.uipanelOther2, 'Visible', 'On');
set(MainHandle.uipanelOther3, 'Visible', 'On');
set(MainHandle.sliderOther1, 'Min', 2.00, 'Max', 4.00);
if(GetOtherSliderValue1() > 4)
SetOtherSliderValue1(2.00);
elseif(GetOtherSliderValue1() < 2)
SetOtherSliderValue1(2.00);
end
% define constants and orbital shape
% quantum numbers
n = round(GetOtherSliderValue1()); % principal quantum number (shell #)
l = round(GetOtherSliderValue2()); % orbital quantum number (subshell type: s, p, d, f, etc.)
m = round(GetOtherSliderValue3()); % magnetic quantum number (orientation of subshell)
% constants: shape and cutoffs of 3D plots (needs fiddling to get a good plot)
cons.cutoff = 0.75 * 10^(24); % electron density cutoff (where to put isosurface)
cons.resolution = 200; %75; % number of calculations per XYZ dimension
cons.spatialLen = 7; % length of physical space to view over (angstroms)
switch n
case 2
switch l
case 0
cons.spatialLen = 10;
case 1
cons.spatialLen = 7;
end
case 3
switch l
case 0
cons.spatialLen = 20;
case 1
cons.spatialLen = 12;
case 2
cons.spatialLen = 7;
end
case 4
switch l
case 0
cons.spatialLen = 30;
case 1
cons.spatialLen = 18;
case 2
cons.spatialLen = 12;
case 3
cons.spatialLen = 5;
end
otherwise
cons.spatialLen = 50;
end
% constants: scale size of plot (don't play with)
cons.scale = 10^(-9.5); % scaling length of calculation (meters)
cons.meters2ang = 10^(-10); % convert meters to angstroms
cons.a0 = 5.2820 * 10^(-11); % Bohr radius (meters)
% constants: orbital name and color (doesn't affect calculation)
%[ColorIs] = makeColors; % load color values
cons.orbitName = orbitNameIs(n,l,m);% name that appears in figure titles
cons.outerColor = [0.7 0.5 0.5];%ColorIs.red; % color of isosurface
cons.sliceStyle2 = false; % alternate clip plane for PlotCrossSectionIsosurface
%--------------------------------------------------------------------------
% generate XYZ space, convert to spherical radius, theta, and phi
[xSpace, ySpace, zSpace] = make3Dspace(cons);
[theta, phi, r] = convert2polar(xSpace, ySpace, zSpace);
%--------------------------------------------------------------------------
% calculate wave function (3D vector of probability)
WaveFn = psiCalculation(n,l,m,r,theta,phi,cons);
set(MainHandle.uipanelAxes1, 'Title', 'ORBITAL');
set(MainHandle.uipanelAxes2, 'Title', 'ORBITAL CROSS SECTION');
set(MainHandle.figureMain, 'currentaxes', MainHandle.axes1);
PlotSolidIsosurface(xSpace, ySpace, zSpace, WaveFn, cons);
set(MainHandle.figureMain, 'currentaxes', MainHandle.axes2);
PlotCrossSectionIsosurface(xSpace, ySpace, zSpace, WaveFn, cons);
str = 'Click on the Reset button to generate the probability density surface.';
text(0.0 , 0.75, str, 'FontSize', 12, 'Parent', MainHandle.axesEquations);
str = ['Current orbital: ' cons.orbitName];
text(0.0 , 0.25, str, 'FontSize', 12, 'Parent', MainHandle.axesEquations);
HydrogenOrbitalGenerationRunning = 0;
end
%% Mix and make your own hybrid orbitals!
%
% PlotHydrogenMolecularOrbital is a function designed to plot a hydrogen
% orbital. The orbital is defined by the quantum numbers, which in tern
% determine the number of nodes and harmonic frequencies observed in the
% wavefunction. This program is intended both to display the functions and
% to allow the user to mix and match wave functions (such as for hybrid
% orbitals).
%
% Radial nodes are determined by Laguerre polynomials, and angular nodes by
% Legendre polynomials. Details of the calculation are in the radial wave
% function and angular wave function sections.
%
% -------------------------------------------------------------------------
% Some notes on the calculation
%
% Remember that all spatial lengths (angstroms, meters, etc.) are real!
% you may need to play with the settings to get the plot that you want.
%
% As the orbital increases in size, increase cons.spatialLen to see it all
% If orbital is missing parts, maybe decrease cons.cutoff by a magnitude
% Increase cons.resolution to make the plot prettier
% remember this makes an N^3 increase in computional time
% The wave function is a cubic 3D vector. Keep that in mind when making
% hybrid orbitals
% Some XYZ axis rotations were needed to align the calculations to Matlab's
% polar 3D space.
%
% -------------------------------------------------------------------------
% notes on the plots
%
% a small function "makeColors" is included to give some preloaded color
% values. This is useful for coloring the skin of the orbitals
% the functions PlotSolidIsosurface, PlotCrossSectionIsosurface, and
% PlotWaveFnSignIsosurface are a good start to visualizing the data
% PlotCrossSectionIsosurface has a color bar. These are multiples of the
% cutoff value labeled in cons.cutoff
% The cons.sliceStyle2 option is a boolean that switches the clipping plane
% from YZ to XZ in the PlotCrossSectionIsosurface plot. This is useful
% for visualizing the inside of certain orbitals
%
%==========================================================================
%% calculate wave function
%==========================================================================
% the wave function is a 3D vector of size [resolution, resolution, resolution]
% calculate it by multiplying each element of the radial and angular components
function [WaveFn] = psiCalculation(n,l,m,r,theta,phi,cons)
WaveFn = radialCalculation(n,l,r,cons) .* angularCalculation(l,m,theta,phi);
% correction 1: remove NaN at atomic nucleus
center = ceil(cons.resolution/2);
WaveFn(center, center, center) = 0;
% correction 2: flip wave function properly when m < 0
if (m < 0 )
WaveFn = permute(WaveFn, [2 1 3]);
end
end
%% radial wave function
% the radial component is composed of two parts: an exponential term and a
% polynomial term. The exponential term adds attraction to the nucleus of
% the atom. The polynomial term adds electron shell harmonics to create
% nodal spheres
function [RadialFn] = radialCalculation(n,l,r,cons)
% import contants
a0 = cons.a0;
% scaling factors
scalFac1 = sqrt((2/(a0*n))^3 * factorial(n-l-1)/(2*n*factorial(n+l)));
scalFac2 = 1/factorial(n - l + 2*l);
% Part 1: exponential component (attraction to nucleus)
nuclearComponent = (2*r/(a0*n)) .* exp(-r/(a0*n));
% Part 2: polynomial component (generates radial nodes)
radialNodeComponent = LaguerrePolynomial(n-l-1, 2*l+1, 2*r/(a0*n));
% combine components to calculate radial wave function
RadialFn = scalFac1 * scalFac2 * nuclearComponent .* radialNodeComponent;
end
% use Laguerre polynomials to introduce nodal spheres into radial function
function [NodalFn] = LaguerrePolynomial(n,m,r)
% initiate polynomial function
NodalFn = zeros(size(r));
% add n coefficient terms to the polynomial
for i = 0:n
polynomialCoeff = factorial(m+n) * nchoosek(m+n,n-i) / factorial(i);
NodalFn = NodalFn + polynomialCoeff * (-r).^i;
end
end
%% angular wave function
% the angular component is a cosine function with Legendre polynomials used
% to add nodal planes.
function [AngularFn] = angularCalculation(l,m,theta,phi)
if (abs(m) == 2)
m = -m;
end
if (m == -2)
phi = phi + pi/4;
end
% normalization and scaling factors
normFac = abs(sign(m)*(2^0.5) + (sign(abs(m)) - 1)*2);
scalFac = sqrt((2*l+1) / (4*pi) * factorial(l-abs(m)) / factorial(l+abs(m)));
% add nodes to spherical harmonics functions
SphFn1 = scalFac * LegendrePolynomial(l,m,cos(theta)) .* exp(1i*m*phi);
SphFn2 = scalFac * LegendrePolynomial(l,-m,cos(theta)) .* exp(1i*-m*phi);
AngularFn = (SphFn1 + SphFn2) / normFac;
end
% use Legendre polynomials to introduce nodal planes into angular function
function [NodalFn] = LegendrePolynomial(l,m,x)
% initiate polynomial function
NodalFn = zeros(size(x));
numCoeffs = floor(1/2*l - 1/2*abs(m));
% add n coefficient terms to the polynomial
for n = 0:numCoeffs
polynomialCoeff = (-1)^n * nchoosek(l-2*n,abs(m)) * nchoosek(l,n) * nchoosek(2*l-2*n,l);
exponent = l - 2*n - abs(m);
NodalFn = NodalFn + polynomialCoeff * x.^exponent;
end
NodalFn = (-1)^m * (1-x.^2).^(abs(m)/2) .* (factorial(abs(m))/2^l*NodalFn);
end
%==========================================================================
%% generate 3D space (X Y Z theta phi r)
%==========================================================================
% generate 3D cartesian space based on inputs
function [xSpace, ySpace, zSpace] = make3Dspace(cons)
% import dimensions and scaling factors
resolution = cons.resolution;
spatialLen = cons.spatialLen;
scale = cons.scale;
% generate XYZ space using meshgrid
xRange = linspace(-spatialLen, spatialLen, resolution) * scale;
yRange = linspace(-spatialLen, spatialLen, resolution) * scale;
zRange = linspace(-spatialLen, spatialLen, resolution) * scale;
[xSpace, ySpace, zSpace] = meshgrid(xRange, yRange, zRange);
end
% most of this function is equivalent to the "cart2sph" function.
% Matlab interprets angles a little differently than a classic calculus
% textbook, as in the engineering-style of polar coordinatles.
% phi and theta are swapped, and the zero-angle is at a -pi/2 angle.
% Consequently we manually convert the points here.
function [theta, phi, r] = convert2polar(x, y, z)
r = sqrt(x.^2+y.^2+z.^2);
theta = acos(z./r); % this is "phi" in the "cart2sph" function
phi = atan2(y,x); % this is "theta" in the "cart2sph" function
end
%==========================================================================
%% plot wave functions
%==========================================================================
% load up some useful color values
function [ColorIs] = makeColors
ColorIs.red = [1 0 0];
ColorIs.green = [0 1 0];
ColorIs.blue = [0 0 1];
ColorIs.purple = [1 0 1];
ColorIs.cyan = [0 1 1];
ColorIs.yellow = [1 1 0];
ColorIs.black = [0 0 0];
ColorIs.grey = [0.3 0.3 0.3];
end
% convert n l m into a useful name
function [orbitName] = orbitNameIs(n,l,m)
subShells = {'s', 'p', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'};
thisM = [num2str(m) num2str(m)];
thisMtmp = num2str(m);
for j = 1:length(thisMtmp)
thisM(2 * j - 1) = '_';
thisM(2 * j) = thisMtmp(j);
end
orbitName = [num2str(n) subShells{l+1} thisM];
end
% plot a solid isosurface of the orbital
function PlotSolidIsosurface(xSpace, ySpace, zSpace, WaveFn, cons)
% import dimensions and scaling factors
spatialLen = cons.spatialLen;
meters2ang = cons.meters2ang;
cutoff = cons.cutoff;
orbitName = cons.orbitName;
isoColor = cons.outerColor;
% square the wavefunction to make an electron density map
WaveFn2 = WaveFn .* conj(WaveFn);
% convert inputs to convenient numbers and values
x = xSpace / meters2ang;
y = ySpace / meters2ang;
z = zSpace / meters2ang;
v = WaveFn2 / cutoff;
% patch and interpret isosurface for better coloration
p = patch(isosurface(x,y,z,v,1));
isonormals(x,y,z,v,p);
set(p,'FaceColor',isoColor,'EdgeColor','none');
% lighting, aspect ratio, plot options
daspect([1 1 1]);
view(3);
axis vis3d;
camlight;
lighting phong;
xlabel('x','FontSize',10);
ylabel('y','FontSize',10);
zlabel('z','FontSize',10);
%title([orbitName ' orbital'],'FontSize',10);
rotate3d on;
% dimensions of plot
plotScale = spatialLen * 1.4;
global MainHandle; %stores the handle for MainGUI
xlim(MainHandle.axes1, [-plotScale plotScale]);
ylim(MainHandle.axes1, [-plotScale plotScale]);
zlim(MainHandle.axes1, [-plotScale plotScale]);
end
% plot a cross section of a solid isosurface of the orbital
function PlotCrossSectionIsosurface(xSpace, ySpace, zSpace, WaveFn, cons)
% import dimensions and scaling factors
spatialLen = cons.spatialLen;
meters2ang = cons.meters2ang;
cutoff = cons.cutoff;
orbitName = cons.orbitName;
isoColor = cons.outerColor;
sliceStyle2 = cons.sliceStyle2;
% use alternate clipping plane?
halfLength = 0;
clipRange = [nan,nan,halfLength,nan,nan,nan];
if (sliceStyle2 == true)
clipRange = [halfLength,nan,nan,nan,nan,nan];
end
% square the wavefunction to make an electron density map
WaveFn2 = WaveFn .* conj(WaveFn);
% convert inputs to convenient numbers and values
x = xSpace / meters2ang;
y = ySpace / meters2ang;
z = zSpace / meters2ang;
v = WaveFn2 / cutoff;
% slice off half the isosurface, change XYZ accordingly
[x,y,z,v] = subvolume(x,y,z,v,clipRange);
% patch and interpret isosurface for better coloration
p1 = patch(isosurface(x,y,z,v,1),'FaceColor',isoColor,'EdgeColor','none');
isonormals(x,y,z,v,p1);
patch(isocaps(x,y,z,v,1),'FaceColor','interp','EdgeColor','none');
% lighting, aspect ratio, plot options
daspect([1 1 1]);
view(3);
axis vis3d;
camlight;
lighting phong;
xlabel('x','FontSize',10);
ylabel('y','FontSize',10);
zlabel('z','FontSize',10);
%title([orbitName ' orbital cross section'],'FontSize',10);
rotate3d on;
% dimensions of plot
plotScale = spatialLen * 1.4;
global MainHandle; %stores the handle for MainGUI
xlim(MainHandle.axes2, [-plotScale plotScale]);
ylim(MainHandle.axes2, [-plotScale plotScale]);
zlim(MainHandle.axes2, [-plotScale plotScale]);
end |
github | arvind96/Quantum-Mechanics-Simulations-master | MainGUI.m | .m | Quantum-Mechanics-Simulations-master/MainGUI.m | 23,097 | utf_8 | b9465e2244f464f5377c58a8ad119079 | function varargout = MainGUI(varargin)
% MAINGUI MATLAB code for MainGUI.fig
% MAINGUI, by itself, creates a new MAINGUI or raises the existing
% singleton*.
%
% H = MAINGUI returns the handle to a new MAINGUI or the handle to
% the existing singleton*.
%
% MAINGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MAINGUI.M with the given input arguments.
%
% MAINGUI('Property','Value',...) creates a new MAINGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before MainGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to MainGUI_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 MainGUI
% Last Modified by GUIDE v2.5 01-Nov-2016 18:30:46
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @MainGUI_OpeningFcn, ...
'gui_OutputFcn', @MainGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before MainGUI is made visible.
function MainGUI_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 MainGUI (see VARARGIN)
% Choose default command line output for MainGUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes MainGUI wait for user response (see UIRESUME)
% uiwait(handles.figureMain);
global MainHandle;
MainHandle = handles;
Start();
% --- Outputs from this function are returned to the command line.
function varargout = MainGUI_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes when figureMain is resized.
function figureMain_SizeChangedFcn(hObject, eventdata, handles)
% hObject handle to figureMain (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global SizeChangeCalled;
if(SizeChangeCalled == 0)
SizeChangeCalled = 1;
pause(0.1);
SizeChangeCalled = 0;
OnMainFigureSizeChanged();
end
% --- Executes when user attempts to close figureMain.
function figureMain_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figureMain (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Quit();
% --------------------------------------------------------------------
function menu_Help_Callback(hObject, eventdata, handles)
% hObject handle to menu_Help (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_About_Callback(hObject, eventdata, handles)
% hObject handle to menu_About (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global AboutHandle;
if(isempty(AboutHandle) || ~ishandle(AboutHandle))
AboutHandle = openfig('AboutGUI.fig', 'visible');
end
figure(AboutHandle);
movegui(AboutHandle,'center');
% --------------------------------------------------------------------
function menu_Exit_Callback(hObject, eventdata, handles)
% hObject handle to menu_Exit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Quit();
% --------------------------------------------------------------------
function menu_ParticleInBox_Callback(hObject, eventdata, handles)
% hObject handle to menu_ParticleInBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_ParticleInBox_1D_Callback(hObject, eventdata, handles)
% hObject handle to menu_ParticleInBox_1D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetCurrentSimulation(11);
Reset();
% --------------------------------------------------------------------
function menu_ParticleInBox_2D_Callback(hObject, eventdata, handles)
% hObject handle to menu_ParticleInBox_2D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetCurrentSimulation(12);
Reset();
% --------------------------------------------------------------------
function menu_HarmonicsOscillator_Callback(hObject, eventdata, handles)
% hObject handle to menu_HarmonicsOscillator (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbuttonPlayPause.
function pushbuttonPlayPause_Callback(hObject, eventdata, handles)
% hObject handle to pushbuttonPlayPause (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Simulate();
% --- Executes on button press in pushbuttonStepNext.
function pushbuttonStepNext_Callback(hObject, eventdata, handles)
% hObject handle to pushbuttonStepNext (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbuttonStepBack.
function pushbuttonStepBack_Callback(hObject, eventdata, handles)
% hObject handle to pushbuttonStepBack (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbuttonReset.
function pushbuttonReset_Callback(hObject, eventdata, handles)
% hObject handle to pushbuttonReset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Reset();
% --- Executes on slider movement.
function sliderTimeScale_Callback(hObject, eventdata, handles)
% hObject handle to sliderTimeScale (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
SetTimeScale(get(hObject, 'Value'));
% --- Executes during object creation, after setting all properties.
function sliderTimeScale_CreateFcn(hObject, eventdata, handles)
% hObject handle to sliderTimeScale (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
% --------------------------------------------------------------------
function context_TimeScale_200x_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale_200x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetTimeScale(2.00);
% --------------------------------------------------------------------
function context_TimeScale_150x_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale_150x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetTimeScale(1.50);
% --------------------------------------------------------------------
function context_TimeScale_100x_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale_100x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetTimeScale(1.00);
% --------------------------------------------------------------------
function context_TimeScale_75x_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale_75x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetTimeScale(0.75);
% --------------------------------------------------------------------
function context_TimeScale_50x_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale_50x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetTimeScale(0.50);
% --------------------------------------------------------------------
function context_TimeScale_25x_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale_25x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetTimeScale(0.25);
% --------------------------------------------------------------------
function context_TimeScale_0x_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale_0x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetTimeScale(0.00);
% --------------------------------------------------------------------
function MyContextMenu_Callback(hObject, eventdata, handles)
% hObject handle to MyContextMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function context_TimeScale_Callback(hObject, eventdata, handles)
% hObject handle to context_TimeScale (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on slider movement.
function sliderC1_Callback(hObject, eventdata, handles)
% hObject handle to sliderC1 (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
SetWaveInC1(get(hObject, 'Value'));
if(GetWaveInC1Priority() ~= 3)
SetWaveInC1Priority(3);
SetWaveInC2Priority(GetWaveInC2Priority() - 1);
SetWaveInC3Priority(GetWaveInC3Priority() - 1);
end
NormalizeC();
% --- Executes during object creation, after setting all properties.
function sliderC1_CreateFcn(hObject, eventdata, handles)
% hObject handle to sliderC1 (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
% --- Executes on slider movement.
function sliderC2_Callback(hObject, eventdata, handles)
% hObject handle to sliderC2 (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
SetWaveInC2(get(hObject, 'Value'));
if(GetWaveInC2Priority() ~= 3)
SetWaveInC1Priority(GetWaveInC1Priority() - 1);
SetWaveInC2Priority(3);
SetWaveInC3Priority(GetWaveInC3Priority() - 1);
end
NormalizeC();
% --- Executes during object creation, after setting all properties.
function sliderC2_CreateFcn(hObject, eventdata, handles)
% hObject handle to sliderC2 (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
% --- Executes on slider movement.
function sliderC3_Callback(hObject, eventdata, handles)
% hObject handle to sliderC3 (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
SetWaveInC3(get(hObject, 'Value'));
if(GetWaveInC3Priority() ~= 3)
SetWaveInC1Priority(GetWaveInC1Priority() - 1);
SetWaveInC2Priority(GetWaveInC2Priority() - 1);
SetWaveInC3Priority(3);
end
NormalizeC();
% --- Executes during object creation, after setting all properties.
function sliderC3_CreateFcn(hObject, eventdata, handles)
% hObject handle to sliderC3 (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
% --------------------------------------------------------------------
function menuOpen_Callback(hObject, eventdata, handles)
% hObject handle to menuOpen (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_HarmonicsOscillator_1D_Callback(hObject, eventdata, handles)
% hObject handle to menu_HarmonicsOscillator_1D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetCurrentSimulation(21);
Reset();
% --------------------------------------------------------------------
function menu_HarmonicsOscillator_2D_Callback(hObject, eventdata, handles)
% hObject handle to menu_HarmonicsOscillator_2D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetCurrentSimulation(22);
Reset();
% --------------------------------------------------------------------
function menu_FreeParticle_Callback(hObject, eventdata, handles)
% hObject handle to menu_FreeParticle (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_FiniteSquareWell_Callback(hObject, eventdata, handles)
% hObject handle to menu_FiniteSquareWell (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_FiniteSquareWell_1D_Callback(hObject, eventdata, handles)
% hObject handle to menu_FiniteSquareWell_1D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetCurrentSimulation(31);
Reset();
% --------------------------------------------------------------------
function menu_HydrogenAtom_Callback(hObject, eventdata, handles)
% hObject handle to menu_HydrogenAtom (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_HydrogenAtom_ProbabilityDensity_Callback(hObject, eventdata, handles)
% hObject handle to menu_HydrogenAtom_ProbabilityDensity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SetCurrentSimulation(51);
Reset();
% --------------------------------------------------------------------
function menu_FiniteSquareWell_2D_Callback(hObject, eventdata, handles)
% hObject handle to menu_FiniteSquareWell_2D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_FreeParticle_1D_Callback(hObject, eventdata, handles)
% hObject handle to menu_FreeParticle_1D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_FreeParticle_2D_Callback(hObject, eventdata, handles)
% hObject handle to menu_FreeParticle_2D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on slider movement.
function sliderOther3_Callback(hObject, eventdata, handles)
% hObject handle to sliderOther3 (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
SetOtherSliderValue3(get(hObject, 'Value'));
% --- Executes during object creation, after setting all properties.
function sliderOther3_CreateFcn(hObject, eventdata, handles)
% hObject handle to sliderOther3 (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
% --- Executes on slider movement.
function sliderOther2_Callback(hObject, eventdata, handles)
% hObject handle to sliderOther2 (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
SetOtherSliderValue2(get(hObject, 'Value'));
% --- Executes during object creation, after setting all properties.
function sliderOther2_CreateFcn(hObject, eventdata, handles)
% hObject handle to sliderOther2 (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
% --- Executes on slider movement.
function sliderOther1_Callback(hObject, eventdata, handles)
% hObject handle to sliderOther1 (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
SetOtherSliderValue1(get(hObject, 'Value'));
% --- Executes during object creation, after setting all properties.
function sliderOther1_CreateFcn(hObject, eventdata, handles)
% hObject handle to sliderOther1 (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
% --------------------------------------------------------------------
function menu_Tools_Callback(hObject, eventdata, handles)
% hObject handle to menu_Tools (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_View_Callback(hObject, eventdata, handles)
% hObject handle to menu_View (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_Tools_Zoom_Callback(hObject, eventdata, handles)
% hObject handle to menu_Tools_Zoom (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
zoom;
% --------------------------------------------------------------------
function menu_Tools_Pan_Callback(hObject, eventdata, handles)
% hObject handle to menu_Tools_Pan (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
pan;
% --------------------------------------------------------------------
function menu_Tools_Rotate3D_Callback(hObject, eventdata, handles)
% hObject handle to menu_Tools_Rotate3D (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rotate3d;
|
github | arvind96/Quantum-Mechanics-Simulations-master | AboutGUI.m | .m | Quantum-Mechanics-Simulations-master/AboutGUI.m | 2,805 | utf_8 | ff0e33b2df131ffeef7d28442adfc2f3 | function varargout = AboutGUI(varargin)
% ABOUTGUI MATLAB code for AboutGUI.fig
% ABOUTGUI, by itself, creates a new ABOUTGUI or raises the existing
% singleton*.
%
% H = ABOUTGUI returns the handle to a new ABOUTGUI or the handle to
% the existing singleton*.
%
% ABOUTGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in ABOUTGUI.M with the given input arguments.
%
% ABOUTGUI('Property','Value',...) creates a new ABOUTGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before AboutGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to AboutGUI_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 AboutGUI
% Last Modified by GUIDE v2.5 24-Aug-2016 01:32:14
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @AboutGUI_OpeningFcn, ...
'gui_OutputFcn', @AboutGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before AboutGUI is made visible.
function AboutGUI_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 AboutGUI (see VARARGIN)
% Choose default command line output for AboutGUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes AboutGUI wait for user response (see UIRESUME)
% uiwait(handles.figureAbout);
% --- Outputs from this function are returned to the command line.
function varargout = AboutGUI_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;
|
github | arvind96/Quantum-Mechanics-Simulations-master | ParticleInBoxDiffWave.m | .m | Quantum-Mechanics-Simulations-master/ParticleInBoxDiffWave.m | 410 | utf_8 | 704d76e4545c7557b2ea35e4d41b1f78 | function [z] = ParticleInBoxDiffWave(L, c1, c2, c3, x, t)
z = c1 * (2/L)^0.5 * (1*pi / L) *cos(1*pi*x / L) * exp(-1i*CalculateEnergy(1, L)*t / 1) + + c2 * (2/L)^0.5 * (2*pi / L) *cos(2*pi*x / L) * exp(-1i*CalculateEnergy(2, L)*t / 1) + c3 * (2/L)^0.5 * (3*pi / L) *cos(3*pi*x / L) * exp(-1i*CalculateEnergy(3, L)*t / 1);
end
function e = CalculateEnergy(n, L)
e = (n^2 * pi^2 * 1) / (2 * 1 * L^2);
end |
github | arvind96/Quantum-Mechanics-Simulations-master | ParticleInFiniteBoxWave.m | .m | Quantum-Mechanics-Simulations-master/ParticleInFiniteBoxWave.m | 1,768 | utf_8 | 966c7dfe606ca2090b66ddd56ee0bfcc | function [z] = ParticleInFiniteBoxWave(c1, c2, c3, x, t)
%returns the wavefunction with center of box as origin and length L
%v1 = 1.28
%v2 = 2.54
%v3 = 3.73
L = 10;
if(x < -L/2) %-Inf to -L/2
z = c1 * 27.5606 * exp((2 * (0.632 - CalculateEnergy(1.28, L)))^0.5 * x) * exp(-1i * CalculateEnergy(1.28, L) * t / 1);
elseif(x < L/2) %-L/2 to L/2
z = c1 * 0.4033 * 1 * cos((2 * CalculateEnergy(1.28, L)) ^ 0.5 * x) * exp(-1i * CalculateEnergy(1.28, L) * t / 1);
else %L/2 to Inf
z = c1 * 27.5606 * exp(-(2 * (0.632 - CalculateEnergy(1.28, L)))^0.5 * x) * exp(-1i * CalculateEnergy(1.28, L) * t / 1);
end
if(x < -L/2) %-Inf to -L/2
z = z + c2 * (-1) * (8.4501) * exp((2 * (0.632 - CalculateEnergy(2.54, L)))^0.5 * x) * exp(-1i * CalculateEnergy(2.54, L) * t / 1);
elseif(x < L/2) %-L/2 to L/2
z = z + c2 * 0.0985 * 1 * sin((2 * CalculateEnergy(2.54, L)) ^ 0.5 * x) * exp(-1i * CalculateEnergy(2.54, L) * t / 1);
else %L/2 to Inf
z = z + c2 * (8.4501) * exp(-(2 * (0.632 - CalculateEnergy(2.54, L)))^0.5 * x) * exp(-1i * CalculateEnergy(2.54, L) * t / 1);
end
if(x < -L/2) %-Inf to -L/2
z = z + c3 * (-21.9790) * exp((2 * (0.632 - CalculateEnergy(3.73, L)))^0.5 * x) * exp(-1i * CalculateEnergy(3.73, L) * t / 1);
elseif(x < L/2) %-L/2 to L/2
z = z + c3 * (0.3940) * 1 * cos((2 * CalculateEnergy(3.73, L)) ^ 0.5 * x) * exp(-1i * CalculateEnergy(3.73, L) * t / 1);
else %L/2 to Inf
z = z + c3 * (-21.9790) * exp(-(2 * (0.632 - CalculateEnergy(3.73, L)))^0.5 * x) * exp(-1i * CalculateEnergy(3.73, L) * t / 1);
end
end
function e = CalculateEnergy(Vn, L)
e = (2 * 1 * Vn^2)/(1 * L^2);
end |
github | jehoons/sbie_weinberg-master | savejson.m | .m | sbie_weinberg-master/module/ifa/matlab/libs/jsonlab-1.2/jsonlab/savejson.m | 18,983 | utf_8 | 2f510ad749556cadd303786e2549f30a | function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('filename',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(filename, 'wb');
fwrite(fid,json);
else
fid = fopen(filename, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt={};
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
bracketlevel=~jsonopt('singletcell',1,varargin{:});
if(len>bracketlevel)
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; name='';
else
txt={padding0, '[', nl};
end
elseif(len==0)
if(~isempty(name))
txt={padding0, '"' checkname(name,varargin{:}) '": []'}; name='';
else
txt={padding0, '[]'};
end
end
for i=1:dim(1)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for j=1:dim(2)
txt{end+1}=obj2json(name,item{i,j},level+(dim(1)>1)+(len>bracketlevel),varargin{:});
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>bracketlevel)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt={};
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+forcearray);
nl=ws.newline;
if(isempty(item))
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": []'};
else
txt={padding0, '[]'};
end
return;
end
if(~isempty(name))
if(forcearray)
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(forcearray)
txt={padding0, '[', nl};
end
end
for j=1:dim(2)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt(end+1:end+5)={padding1, '"', checkname(name,varargin{:}),'": {', nl};
else
txt(end+1:end+3)={padding1, '{', nl};
end
if(~isempty(names))
for e=1:length(names)
txt{end+1}=obj2json(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:});
if(e<length(names))
txt{end+1}=',';
end
txt{end+1}=nl;
end
end
txt(end+1:end+2)={padding1,'}'};
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(forcearray)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt={};
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1)
txt={padding1, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(len>1)
txt={padding1, '[', nl};
end
end
for e=1:len
val=escapejsonstring(item(e,:));
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name))
obj=['"',val,'"'];
end
txt(end+1:end+2)={padding1, obj};
else
txt(end+1:end+4)={padding0,'"',val,'"'};
end
if(e==len)
sep='';
end
txt{end+1}=sep;
end
if(len>1)
txt(end+1:end+3)={nl,padding1,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matlabobject2json(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2json(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos))
return;
end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8)
isoct=0;
end
end
if(isoct)
escapechars={'\\','\"','\/','\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\$1');
else
escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\\$1');
end
|
github | jehoons/sbie_weinberg-master | loadjson.m | .m | sbie_weinberg-master/module/ifa/matlab/libs/jsonlab-1.2/jsonlab/loadjson.m | 16,145 | ibm852 | 7582071c5bd7f5e5f74806ce191a9078 | function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once'))
string=fname;
elseif(exist(fname,'file'))
try
string = fileread(fname);
catch
try
string = urlread(['file://',fname]);
catch
string = urlread(['file://',fullfile(pwd,fname)]);
end
end
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
object.(valid_field(str))=val;
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=-1;
if(isfield(varargin{1},'progressbar_'))
pbar=varargin{1}.progressbar_;
end
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
pos=skip_whitespace(pos,inStr,len);
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function newpos=skip_whitespace(pos,inStr,len)
newpos=pos;
while newpos <= len && isspace(inStr(newpos))
newpos = newpos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str);
switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos);
keyboard;
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct
currstr=inStr(pos:min(pos+30,end));
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
if(isfield(varargin{1},'progressbar_'))
waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | jehoons/sbie_weinberg-master | loadubjson.m | .m | sbie_weinberg-master/module/ifa/matlab/libs/jsonlab-1.2/jsonlab/loadubjson.m | 13,300 | utf_8 | b15e959f758c5c2efa2711aa79c443fc | function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
% opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or
% earlier versions (JSONLab 1.0 final or earlier),
% the "name" tag is treated as a string. To load
% these UBJSON data, you need to manually set this
% flag to 1.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
if(jsonopt('NameIsString',0,varargin{:}))
str = parseStr(varargin{:});
else
str = parse_name(varargin{:});
end
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
object.(valid_field(str))=val;
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data, adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object, adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object, adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parse_name(varargin)
global pos inStr
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of name');
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | jehoons/sbie_weinberg-master | saveubjson.m | .m | sbie_weinberg-master/module/ifa/matlab/libs/jsonlab-1.2/jsonlab/saveubjson.m | 17,723 | utf_8 | 3414421172c05225dfbd4a9c8c76e6b3 | function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('filename',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
fid = fopen(filename, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
bracketlevel=~jsonopt('singletcell',1,varargin{:});
len=numel(item); % let's handle 1D cell first
if(len>bracketlevel)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>bracketlevel),varargin{:})];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(len>bracketlevel)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
if(~isempty(name))
if(forcearray)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(forcearray)
txt='[';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt=[txt N_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(forcearray)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(len>1)
txt='[';
end
end
for e=1:len
val=item(e,:);
if(len==1)
obj=[N_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name))
obj=['',S_(val),''];
end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[N_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[N_(checkname(name,varargin{:})) numtxt];
else
txt=[N_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,N_('_ArrayIsComplex_'),'T'];
end
txt=[txt,N_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,N_('_ArrayIsComplex_'),'T'];
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matlabobject2ubjson(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2ubjson(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(id~=0))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(id~=0);
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos))
return;
end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=N_(str)
val=[I_(int32(length(str))) str];
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github | jehoons/sbie_weinberg-master | savejson.m | .m | sbie_weinberg-master/module/attractor/fumia/matlab/libs/jsonlab-1.2/jsonlab/savejson.m | 18,983 | utf_8 | 2f510ad749556cadd303786e2549f30a | function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('filename',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(filename, 'wb');
fwrite(fid,json);
else
fid = fopen(filename, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt={};
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
bracketlevel=~jsonopt('singletcell',1,varargin{:});
if(len>bracketlevel)
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; name='';
else
txt={padding0, '[', nl};
end
elseif(len==0)
if(~isempty(name))
txt={padding0, '"' checkname(name,varargin{:}) '": []'}; name='';
else
txt={padding0, '[]'};
end
end
for i=1:dim(1)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for j=1:dim(2)
txt{end+1}=obj2json(name,item{i,j},level+(dim(1)>1)+(len>bracketlevel),varargin{:});
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>bracketlevel)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt={};
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+forcearray);
nl=ws.newline;
if(isempty(item))
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": []'};
else
txt={padding0, '[]'};
end
return;
end
if(~isempty(name))
if(forcearray)
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(forcearray)
txt={padding0, '[', nl};
end
end
for j=1:dim(2)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt(end+1:end+5)={padding1, '"', checkname(name,varargin{:}),'": {', nl};
else
txt(end+1:end+3)={padding1, '{', nl};
end
if(~isempty(names))
for e=1:length(names)
txt{end+1}=obj2json(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:});
if(e<length(names))
txt{end+1}=',';
end
txt{end+1}=nl;
end
end
txt(end+1:end+2)={padding1,'}'};
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(forcearray)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt={};
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1)
txt={padding1, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(len>1)
txt={padding1, '[', nl};
end
end
for e=1:len
val=escapejsonstring(item(e,:));
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name))
obj=['"',val,'"'];
end
txt(end+1:end+2)={padding1, obj};
else
txt(end+1:end+4)={padding0,'"',val,'"'};
end
if(e==len)
sep='';
end
txt{end+1}=sep;
end
if(len>1)
txt(end+1:end+3)={nl,padding1,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matlabobject2json(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2json(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos))
return;
end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8)
isoct=0;
end
end
if(isoct)
escapechars={'\\','\"','\/','\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\$1');
else
escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\\$1');
end
|
github | jehoons/sbie_weinberg-master | loadjson.m | .m | sbie_weinberg-master/module/attractor/fumia/matlab/libs/jsonlab-1.2/jsonlab/loadjson.m | 16,145 | ibm852 | 7582071c5bd7f5e5f74806ce191a9078 | function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once'))
string=fname;
elseif(exist(fname,'file'))
try
string = fileread(fname);
catch
try
string = urlread(['file://',fname]);
catch
string = urlread(['file://',fullfile(pwd,fname)]);
end
end
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
object.(valid_field(str))=val;
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=-1;
if(isfield(varargin{1},'progressbar_'))
pbar=varargin{1}.progressbar_;
end
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
pos=skip_whitespace(pos,inStr,len);
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function newpos=skip_whitespace(pos,inStr,len)
newpos=pos;
while newpos <= len && isspace(inStr(newpos))
newpos = newpos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str);
switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos);
keyboard;
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct
currstr=inStr(pos:min(pos+30,end));
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
if(isfield(varargin{1},'progressbar_'))
waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | jehoons/sbie_weinberg-master | loadubjson.m | .m | sbie_weinberg-master/module/attractor/fumia/matlab/libs/jsonlab-1.2/jsonlab/loadubjson.m | 13,300 | utf_8 | b15e959f758c5c2efa2711aa79c443fc | function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
% opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or
% earlier versions (JSONLab 1.0 final or earlier),
% the "name" tag is treated as a string. To load
% these UBJSON data, you need to manually set this
% flag to 1.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
if(jsonopt('NameIsString',0,varargin{:}))
str = parseStr(varargin{:});
else
str = parse_name(varargin{:});
end
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
object.(valid_field(str))=val;
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data, adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object, adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object, adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parse_name(varargin)
global pos inStr
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of name');
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | jehoons/sbie_weinberg-master | saveubjson.m | .m | sbie_weinberg-master/module/attractor/fumia/matlab/libs/jsonlab-1.2/jsonlab/saveubjson.m | 17,723 | utf_8 | 3414421172c05225dfbd4a9c8c76e6b3 | function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('filename',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
fid = fopen(filename, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
bracketlevel=~jsonopt('singletcell',1,varargin{:});
len=numel(item); % let's handle 1D cell first
if(len>bracketlevel)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>bracketlevel),varargin{:})];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(len>bracketlevel)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
if(~isempty(name))
if(forcearray)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(forcearray)
txt='[';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt=[txt N_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(forcearray)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(len>1)
txt='[';
end
end
for e=1:len
val=item(e,:);
if(len==1)
obj=[N_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name))
obj=['',S_(val),''];
end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[N_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[N_(checkname(name,varargin{:})) numtxt];
else
txt=[N_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,N_('_ArrayIsComplex_'),'T'];
end
txt=[txt,N_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,N_('_ArrayIsComplex_'),'T'];
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matlabobject2ubjson(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2ubjson(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(id~=0))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(id~=0);
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos))
return;
end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=N_(str)
val=[I_(int32(length(str))) str];
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github | LucaDeSiena/MuRAT-master | Murat_test.m | .m | MuRAT-master/bin/Murat_test.m | 4,852 | utf_8 | 52d650fdb0af7a90357016b5a240ec71 | function [image, SAChdr] = Murat_test(nameWaveform,...
centralFrequencies,smoothingC,figOutput,verboseOutput)
% TEST seismogram envelopes for changes in broadening
% CREATES a figure with seismograms and envelopes for different frequencies
%
% Input Parameters:
% nameWaveform: name of the SAC file
% centralFrequencies: vector of frequencies (Hz),if [] no filter
% smoothingCoefficient: coefficient to smooth envelopes
% figOutput: decide if you want to show figures (set 1)
% verboseOutput: decide if you want to show messages (set 1)
%
% Output:
% image: image with envelope at specified frequency
% SAChdr: header of the SAC file
%
% Imports SAC files
[times,sisma,SAChdr] = fget_sac(nameWaveform);
image = [];
%% Figure
if figOutput == 1
srate_i = 1/SAChdr.times.delta;
sisma = detrend(sisma,1);
lsis = length(sisma);
tu = tukeywin(lsis,0.05);
tsisma = tu.*sisma;
image = figure('Name',['Test Seismograms: '...
nameWaveform],'NumberTitle','off','Position',[20,400,1200,1000],...
'visible','off');
lengthFrequencies = length(centralFrequencies);
plotFrequencies = 1:2:2*lengthFrequencies;
if isequal(centralFrequencies,[])
plot(times,sisma,'k-','LineWidth',2);
xlim([SAChdr.times.a - 5 SAChdr.times.a + 20])
SetFDefaults
else
for i = 1:lengthFrequencies
% Filter creation - in loop for each frequency
cf = centralFrequencies(i);
Wn = ([cf-cf/3 cf+cf/3]/srate_i*2);
[z,p,k] = butter(4,Wn,'bandpass');
[sos,g] = zp2sos(z,p,k);
fsisma = filtfilt(sos,g,tsisma);
hsp_i = hilbert(fsisma);
sp_i = smooth(abs(hsp_i),smoothingC/cf*srate_i);
subplot(lengthFrequencies,2,plotFrequencies(i));
plot(times,fsisma,'k-','LineWidth',2);
xlabel('Time (s)')
ylabel('Amplitude')
SetFDefaults
subplot(lengthFrequencies,2,plotFrequencies(i)+1);
plot(times,sp_i,'k-','LineWidth',2);
xlabel('Time (s)')
ylabel('Energy')
SetFDefaults
end
end
end
%%
% Checking all metadata
if verboseOutput == 1
fprintf('<strong> Checking temporal metadata.</strong>\n');
if isequal(SAChdr.times.o,-12345)
disp('Origin (o) is not set.')
else
disp(['Origin (o) at ' num2str(SAChdr.times.o) ' s.'])
end
if isequal(SAChdr.times.a,-12345)
disp('P wave picking (a) is not set.')
else
disp(['P wave picking (a) at ' num2str(SAChdr.times.a) ' s.'])
end
if isequal(SAChdr.times.t0,-12345)
disp('S wave picking (t0) is not set.')
else
disp(['S wave picking (t0) at ' num2str(SAChdr.times.t0) ' s.'])
end
fprintf('<strong> Checking event location metadata.</strong>\n');
if isequal(SAChdr.event.evla,-12345)
disp('Event latitude (evla) is not set.')
else
disp(['Event latitude (evla) at ' num2str(SAChdr.event.evla)...
' degrees.'])
end
if isequal(SAChdr.event.evlo,-12345)
disp('Event longitude (evlo) is not set.')
else
disp(['Event longitude (evlo) at ' num2str(SAChdr.event.evlo)...
' degrees.'])
end
if isequal(SAChdr.event.evdp,-12345)
disp('Event depth (evdp) is not set.')
else
disp(['Event depth (evdp) at ' num2str(SAChdr.event.evdp) ' km.'])
end
fprintf('<strong> Checking station location metadata.</strong>\n');
if isequal(SAChdr.station.stla,-12345)
disp('Station latitude (stla) is not set.')
else
disp(['Station latitude (stla) at ' num2str(SAChdr.station.stla)...
' degrees.'])
end
if isequal(SAChdr.station.stlo,-12345)
disp('Station longitude (stlo) is not set.')
else
disp(['Station longitude (stlo) at ' num2str(SAChdr.station.stlo)...
' degrees.'])
end
if isequal(SAChdr.station.stel,-12345)
disp('Station elevation (stel) is not set.')
else
disp(['Station elevation (stel) at ' num2str(SAChdr.station.stel)...
' m.'])
end
end
function SetFDefaults()
% DEFAULT settings for MuRAt figures
ax = gca;
ax.GridColor = [0 0 0];
ax.GridLineStyle = '--';
ax.GridAlpha = 0.3;
ax.LineWidth = 1.5;
ax.FontSize = 12;
grid on |
github | LucaDeSiena/MuRAT-master | Murat_Qc.m | .m | MuRAT-master/bin/Murat_Qc.m | 4,811 | utf_8 | c1f465e321541a0c536c806a1c2ed599 | function [inverseQc_i, uncertaintyQc_i] = Murat_Qc(cf,sped,sp_i,...
cursorCodaStart_i,cursorCodaEnd_i,tCoda_i,srate_i,QcMeasurement)
% function [inverseQc_i, uncertaintyQc_i] = Murat_Qc(cf,sped,sp_i,...
% cursorCodaStart_i,cursorCodaEnd_i,tCoda_i,srate_i,QcMeasurement)
%
% MEASURES Qc and its uncertainty.
%
% Input parameters:
% cf: central frequency
% sped: spectral decay
% sp_i: envelopes
% cursorCodaStart_i: start of the coda on trace
% cursorEndStart_i: end of the coda on trace
% tCoda_i: start of the coda in seconds
% srate_i: sampling rate
% QcMeasurement: decides if Linearized or NonLinear solutions
% Output parameters:
% inverseQc_i: inverse coda attenuation factor
% uncertaintyQc_i: uncertainty on inverse coda attenuation factor
lcf = length(cf);
inverseQc_i = zeros(lcf,1);
uncertaintyQc_i = zeros(lcf,1);
for i = 1:lcf
envelopeC =...
sp_i(cursorCodaStart_i:cursorCodaEnd_i,i);
lEnvelopeC = length(envelopeC);
cf_i = cf(i);
if isempty(envelopeC)
inverseQc_i(i) = 0;
uncertaintyQc_i(i) = 0;
else
if isequal(QcMeasurement,'Linearized')
lapseT =...
(tCoda_i+1/srate_i:1/srate_i:tCoda_i+lEnvelopeC/srate_i)';
[linearFit, uncertaintyFit] =...
estimatesLinear(lapseT,envelopeC,lEnvelopeC,sped,cf_i);
if linearFit(1)<0
inverseQc_i(i) = -linearFit(1);
uncertaintyQc_i(i) = abs(uncertaintyFit(1,2));
else
inverseQc_i(i) = 0;
uncertaintyQc_i(i) = 0;
end
elseif isequal(QcMeasurement,'NonLinear')
QValues = 0:10^-5:10^-1;
lWindow =...
round((cursorCodaEnd_i-cursorCodaStart_i)/srate_i);
lapseT =...
(tCoda_i+0.5:tCoda_i+lWindow-0.5)';
[nonLinearFit, uncertaintyFit] = estimatesNonLinear(lapseT,...
envelopeC,QValues,sped,lWindow,cf_i,srate_i);
inverseQc_i(i) = nonLinearFit;
uncertaintyQc_i(i) = uncertaintyFit;
else
error('Unknown strategy to calculate Qc');
end
end
end
uncertaintyQc_i(inverseQc_i==0) = 0;
end
%%
% Calculations in the linarized case.
function [linearFit, uncertaintyFit] =...
estimatesLinear(lapseT,envelopeC,lEnvelopeC,sped,cf_i)
%Only evaluate central time series
edgeC = floor(0.05*lEnvelopeC);
lapseTime = lapseT(edgeC:end-edgeC);
spcm1 = envelopeC(edgeC:end-edgeC);
weigthEnergy = spcm1.*lapseTime.^sped;
logWEnergy = log(weigthEnergy)/2/pi/cf_i;
linearFit =...
polyfit(lapseTime,logWEnergy,1);
uncertaintyFit =...
corrcoef([lapseTime,logWEnergy]);
end
%%
%%
% Calculations in the non-linar (grid-search) case.
function [nonLinearFit, uncertaintyFit] =...
estimatesNonLinear(lapseT,envelopeC,QValues,sped,lWindow,cf_i,srate_i)
lQValues = length(QValues);
dObs = zeros(lWindow,1);
for k = 1:lWindow
ntm = (k-1)*srate_i + 1:k*srate_i;
dObs(k,1) = mean(envelopeC(floor(ntm)));
end
dObserved = dObs(1:end-1)/dObs(end);
E = zeros(lQValues,1);
for n = 1:lQValues
dPre =...
lapseT.^(-sped).*exp(-2*pi*cf_i.*lapseT*QValues(n));
dPredicted = dPre(1:end-1)/dPre(end);
E(n,1) =...
sum(abs(dObserved-dPredicted));
end
[Emin, indexEmin] = min(E);
nonLinearFit = QValues(indexEmin);
uncertaintyFit = 1/Emin;
end
|
github | LucaDeSiena/MuRAT-master | Murat_velocity.m | .m | MuRAT-master/bin/Murat_velocity.m | 1,488 | utf_8 | 1de5fbc525bde1a813520c7f5bac4afc | % FUNCTION Murat_velocity: It finds the velocity at the point (xx,yy,zz) by
% linear interpolation.
function v = Murat_velocity(xx,yy,zz,gridD,pvel)
%
% CALCULATES the velocity at xx, yy, and zz by linear interpolation
%
% Input parameters:
% xx: x point
% yy: y point
% zz: z point
% gridD: grid of ray tracing
% pvel: velocity model for ray tracing
%
% Output parameters:
% v: velocity
xGrid = gridD.x;
yGrid = gridD.y;
zGrid = gridD.z;
[ip,jp,kp,flag] = Murat_cornering(xx,yy,zz,gridD);
if flag>0
v = pvel(jp,ip,kp);
return
end
ip1 = ip+1;
jp1 = jp+1;
kp1 = kp+1;
xd = xGrid(ip1) - xGrid(ip);
yd = yGrid(jp1) - yGrid(jp);
zd = zGrid(kp1) - zGrid(kp);
xf = (xx - xGrid(ip))/xd;
yf = (yy - yGrid(jp))/yd;
zf = (zz - zGrid(kp))/zd;
v1 = pvel(jp,ip,kp) + (pvel(jp1,ip,kp) -pvel(jp,ip,kp))*xf;
v2 = pvel(jp,ip1,kp)+(pvel(jp1,ip1,kp) -pvel(jp,ip1,kp))*xf;
v3 = v1 + (v2 - v1)*yf;
v4 = pvel(jp,ip,kp1)+(pvel(jp1,ip,kp1) -pvel(jp,ip,kp1))*xf;
v5 = pvel(jp,ip1,kp1)+...
(pvel(jp1,ip1,kp1) - pvel(jp,ip1,kp1))*xf;
v6 = v4 + (v5 - v4)*yf;
v = v3 + (v6 - v3)*zf;
end |
github | LucaDeSiena/MuRAT-master | Murat_dataParallelized.m | .m | MuRAT-master/bin/Murat_dataParallelized.m | 9,743 | utf_8 | 556beb9aa8bf6ba90035092e662c94d3 | function Murat = Murat_dataParallelized(Murat)
% MEASURES Qc, peak-delay and Q for each seismic trace located in a folder.
% This code is a collection of functions that do all the necessary.
% Inputs
listSac = Murat.input.listSac;
lengthData = length(listSac);
compon = Murat.input.components;
modv = Murat.input.modv;
lengthParameterModel = length(modv(:,1));
gridStep = [Murat.input.gridStepX/2 ...
Murat.input.gridStepY/2 (modv(2,3) - modv(1,3))/2];
modvQc = [modv(:,1) + gridStep(1)...
modv(:,2)+gridStep(2) modv(:,3)+gridStep(3)];
gridD = Murat.input.gridPropagation;
pvel = Murat.input.pvel;
cf = Murat.input.centralFrequency;
lcf = length(cf);
origin = Murat.input.origin;
originTime = Murat.input.originTime;
PTime = Murat.input.PTime;
STime = Murat.input.STime;
PorS = Murat.input.POrS;
tCm = Murat.input.startLapseTime;
vP = Murat.input.averageVelocityP;
vS = Murat.input.averageVelocityS;
maxtpde = Murat.input.maximumPeakDelay;
tWm = Murat.input.codaWindow;
sped = Murat.input.spectralDecay;
kT = Murat.input.kernelTreshold;
B0 = Murat.input.albedo;
Le1 = Murat.input.extinctionLength;
bodyWindow = Murat.input.bodyWindow;
startNoise = Murat.input.startNoise;
QcM = Murat.input.QcMeasurement;
lapseTimeMethod = Murat.input.lapseTimeMethod;
maxtravel = Murat.input.maxtravel;
% Set up variables to save
locationDeg = zeros(lengthData,6);
locationM = zeros(lengthData,6);
theoreticalTime = zeros(lengthData,1);
totalLengthRay = zeros(lengthData,1);
peakDelay = zeros(lengthData,lcf);
inverseQc = zeros(lengthData,lcf);
uncertaintyQc = zeros(lengthData,lcf);
energyRatioBodyCoda = zeros(lengthData,lcf);
energyRatioCodaNoise = zeros(lengthData,lcf);
raysPlot = zeros(100,5,lengthData);
tCoda = zeros(lengthData,lcf);
inversionMatrixPeakDelay =...
zeros(lengthData,lengthParameterModel);
inversionMatrixQ =...
zeros(lengthData,lengthParameterModel);
inversionMatrixQc =...
zeros(lengthData,lengthParameterModel);
rayCrossing =...
zeros(lengthData,lengthParameterModel);
%=========================================================================
% Count waveforms that must be eliminated because of peak-delay contraints
% on peak delays and coda attenuation.
count_trash = 0;
parfor i = 1:lengthData
if isequal(mod(i,100),0)
disp(['Waveform number is ', num2str(i)])
end
listSac_i = listSac{i};
% Calculates envelopes
[tempis,sp_i,SAChdr_i,srate_i] = Murat_envelope(cf,listSac_i);
% Set earthquake and stations locations in degrees or meters
[locationDeg_i, locationM_i] =...
Murat_location(origin,SAChdr_i);
locationDeg(i,:) = locationDeg_i;
% Checks direct-wave picking on the trace and outputs it
[cursorPick_i, pktime_i, v_i] = Murat_picking(tempis,...
PTime,STime,PorS,vP,vS,srate_i,listSac_i,SAChdr_i);
% Conditions in case the zero time is missing in the header
[theoreticalTime_i, originTime_i] =...
Murat_originTime(pktime_i,originTime,v_i,locationM_i,SAChdr_i,i);
% Calculates the window where to search for peak delay
cursorPeakDelay_i =...
Murat_peakDelayCheck(tempis,cursorPick_i,maxtpde,srate_i);
% Calculates peak delay time
peakDelay_i =...
Murat_peakDelay(sp_i,cursorPick_i,srate_i,cursorPeakDelay_i);
% Calculates rays for the right component
calculateRays = recognizeComponents(i,compon);
if calculateRays
% All the ray-dependent parameters
[Apd_i, AQ_i, totalLengthRay_i, raysPlot_i, rayCrossing_i]...
=...
Murat_rays(modv,gridD,pvel,locationM_i);
inversionMatrixPeakDelay(i,:) = Apd_i;
inversionMatrixQ(i,:) = AQ_i;
totalLengthRay(i,1) = totalLengthRay_i;
raysPlot(:,:,i) = raysPlot_i;
rayCrossing(i,:) = rayCrossing_i;
end
% Sets the lapse time
[tCoda_i, cursorCodaStart_i,...
cursorCodaEnd_i] =...
Murat_codaCheck(originTime_i,pktime_i,srate_i,tCm,tWm,tempis,...
peakDelay_i,lapseTimeMethod);
if (cursorCodaEnd_i - cursorCodaStart_i) < (tWm*srate_i)-2 || ...
(pktime_i-originTime_i)>maxtravel
locationM(i,:) = locationM_i;
theoreticalTime(i,1) = theoreticalTime_i;
peakDelay(i,:) = NaN;
inverseQc(i,:) = NaN;
uncertaintyQc(i,:) = NaN;
energyRatioBodyCoda(i,:) = NaN;
energyRatioCodaNoise(i,:) = NaN;
tCoda(i,:) = tCoda_i;
count_trash = count_trash +1;
continue
end
% Measures Qc and its uncertainty
[inverseQc_i, uncertaintyQc_i] = Murat_Qc(cf,sped,...
sp_i,cursorCodaStart_i,cursorCodaEnd_i,tCoda_i,srate_i,QcM);
% Decide if you calculate kernels
calculateKernels = recognizeComponents(i,compon);
if calculateKernels
% Calculates kernels
[K_grid, r_grid] =...
Murat_kernels(tCoda_i+tWm/2,locationM_i(1:3),...
locationM_i(4:6),modvQc,vS,kT,B0,Le1,lapseTimeMethod);
% Calculates matrix
AQc_i =...
Murat_codaMatrix(modvQc,K_grid,r_grid,0,[],[]);
inversionMatrixQc(i,:) = AQc_i;
end
% Measures Q
[energyRatioBodyCoda_i,energyRatioCodaNoise_i]=...
Murat_body(bodyWindow,startNoise,srate_i,sp_i,cursorPick_i,...
cursorCodaStart_i,cursorCodaEnd_i);
% Saving
locationM(i,:) = locationM_i;
theoreticalTime(i,1) = theoreticalTime_i;
peakDelay(i,:) = peakDelay_i;
inverseQc(i,:) = inverseQc_i;
uncertaintyQc(i,:) = uncertaintyQc_i;
energyRatioBodyCoda(i,:) = energyRatioBodyCoda_i;
energyRatioCodaNoise(i,:) = energyRatioCodaNoise_i;
tCoda(i,:) = tCoda_i;
end
% Setting up the final data vectors and matrices with checks on values
Murat.data.locationsDeg = locationDeg;
Murat.data.locationsM = locationM;
Murat.data.theoreticalTime = theoreticalTime;
Murat.data.peakDelay = peakDelay;
Murat.data.inversionMatrixPeakDelay = inversionMatrixPeakDelay;
Murat.data.inversionMatrixQ = inversionMatrixQ;
Murat.data.totalLengthRay = totalLengthRay;
Murat.data.raysPlot = raysPlot;
Murat.data.rayCrossing = sum(rayCrossing);
Murat.data.inverseQc = inverseQc;
Murat.data.uncertaintyQc = uncertaintyQc;
Murat.data.inversionMatrixQc = inversionMatrixQc;
Murat.data.energyRatioBodyCoda = energyRatioBodyCoda;
Murat.data.energyRatioCodaNoise = energyRatioCodaNoise;
Murat.data.tCoda = tCoda;
Murat = Murat_selection(Murat);
ratio = count_trash/lengthData*(100);
disp(['Ratio of removed recordings: ', num2str(ratio)])
if ~isempty(Murat.input.declustering)
Murat =...
Murat_declustering(Murat,Murat.input.declustering);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function calculateValue =...
recognizeComponents(index,components)
% LOGICAL to decide if forward model is necessary depending in waveform
% number (index) and number of components.
calculateValue = isequal(components,1) ||...
(isequal(components,2) || isequal(components,3)) &&...
isequal(mod(index,components),1);
|
github | LucaDeSiena/MuRAT-master | Murat_paasschensFunction.m | .m | MuRAT-master/bin/Murat_paasschensFunction.m | 2,567 | utf_8 | 99c9b500b261025953898c086ccb52b9 | function [t0,A0,N,coda,t] = Murat_paasschensFunction(r,v,B0,Le_1,dt,T)
% function [t0,A0,N,coda,t] = Murat_paasschensFunction(r,v,B0,Le_1,dt,T)
%
% CREATES the Paasschens function for a fixed r, with constants v,B0,Le_1,
% for points in the vector t until t_max given by T.
%
% Structure:
% The Paasschens function is composed of a delta plus a coda:
% The delta is in t0 = r/v;
% The coda starts in t0 = r/v;
% The amplitude of the delta is A0;
% The coda is computed from t0 to T;
% The coda is reported at samples starting at t0;
% Only the N points for which coda is computed are provided.
%
% Sample at t=t0 tends to infinity. As it is integrable, the
% corresponding value is provided:
%
% integral_0^T [E(r,t0+dt)dt] = E(r,t0+T) T 4/3;
%
% the size of the interval is half, so E(r,t0+dt)*2/3 is stored at t=t0.
% This improves accuracy for small dt that are not too small by including
% the sample at t=t0.
%
% Input parameters:
% r: distance to source
% v: velocity
% B0: albedo
% Le_1: extinction length
% dt: time resolution
% T: final time of interest
%
% Output parameters:
% t0: time of the delta and beginning of coda: t0=r/v
% A0: Amplitude of the delta
% N: number of points from t0 to T (or from 0 to T-t0) of coda
% coda: the samples of the coda
% t: time vector
%
% Authors: De La Torre & Del Pezzo, used first in Del Pezzo et al. 2018,
% Geosciences.
t0 = r/v;
t = (t0:dt:(T+2*dt))';
N = length(t);
A0 = exp(-Le_1*v*t0)./(4*pi*r.^2*v);
f1 = (1-t0.*t0./(t.*t)).^(1/8);
f2 = (3*B0*Le_1./(4*pi*v*t)).^(3/2);
f3 = exp(-Le_1*v*t);
x = v*t*B0*Le_1.*(1-t0.*t0./(t.*t)).^(3/4);
f4 = F_function(x);
coda = f1.*f2.*f3.*f4;
coda(1) = coda(2)*2/3;
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function F = F_function(x)
cond = x>1e-30;
F = zeros(size(x));
y = x(cond);
F(cond) = exp(y).*sqrt(1+2.026./(y+1e-30));
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
github | LucaDeSiena/MuRAT-master | Murat_inversion.m | .m | MuRAT-master/bin/Murat_inversion.m | 12,333 | utf_8 | 3cddd5208ee1f1700c76c454229961d6 | %% Peak-delay, Qc and Q TOMOGRAPHIC INVERSIONS
function Murat = Murat_inversion(Murat)
%%
% Importing all the necessary inputs and data for plotting
FLabel = Murat.input.label;
outputLCurve = Murat.input.lCurve;
tWm = Murat.input.codaWindow;
cf = Murat.input.centralFrequency;
sped = Murat.input.spectralDecay;
nxc = Murat.input.gridLong;
nyc = Murat.input.gridLat;
nzc = Murat.input.gridZ;
sizea = Murat.input.sizeCheck;
latt = Murat.input.lowCheck;
hatt = Murat.input.highCheck;
modv = Murat.input.modv;
spike_o = Murat.input.spikeLocationOrigin;
spike_e = Murat.input.spikeLocationEnd;
spike_v = Murat.input.spikeValue;
x = Murat.input.x;
y = Murat.input.y;
z = Murat.input.z;
QcM = Murat.input.QcMeasurement;
inversionMethod = Murat.input.inversionMethod;
lCurveQc = Murat.input.lCurveQc;
lCurveQ = Murat.input.lCurveQ;
origin = Murat.input.origin;
muratHeader = Murat.input.header;
Apd_i =...
Murat.data.inversionMatrixPeakDelay;
Ac_i = Murat.data.inversionMatrixQc;
A_i = Murat.data.inversionMatrixQ;
luntot = Murat.data.totalLengthRay;
time0 = Murat.data.travelTime;
Qm = Murat.data.inverseQc;
RZZ = Murat.data.uncertaintyQc;
lpdelta = Murat.data.variationPeakDelay;
rapsp = Murat.data.energyRatioBodyCoda;
retain_pd = Murat.data.retainPeakDelay;
retain_Qc = Murat.data.retainQc;
retain_Q = Murat.data.retainQ;
ray_crosses_pd = Murat.data.raysPeakDelay;
ray_crosses_Qc = Murat.data.raysQc;
ray_crosses_Q = Murat.data.raysQ;
tCoda = Murat.data.tCoda;
FPath = './';
lMF = size(ray_crosses_pd);
modv_pd = zeros(lMF(1),5,lMF(2));
modv_Qc = zeros(lMF(1),10,lMF(2));
modv_Q = zeros(lMF(1),10,lMF(2));
const_Qc = zeros(size(rapsp));
residualQ = zeros(1,lMF(2));
residualQc = zeros(1,lMF(2));
%%
% Creating folders to store results
if exist(FLabel,'dir')==7
rmdir(FLabel,'s')
end
mkdir(FLabel)
mkdir([FLabel,'/RaysKernels'])
mkdir([FLabel,'/Tests'])
mkdir([FLabel,'/Results'])
mkdir([FLabel,'/Results/PeakDelay'])
mkdir([FLabel,'/Results/Qc'])
mkdir([FLabel,'/Results/Q'])
mkdir([FLabel,'/Results/Parameter'])
mkdir([FLabel,'/Checkerboard'])
mkdir([FLabel,'/Checkerboard/Qc'])
mkdir([FLabel,'/Checkerboard/Q'])
mkdir([FLabel,'/Spike'])
mkdir([FLabel,'/Spike/Qc'])
mkdir([FLabel,'/Spike/Q'])
mkdir([FLabel,'/VTK'])
mkdir([FLabel,'/TXT'])
%%
% Loops over all frequencies and parameter models
for k = 1:lMF(2)
modv_pd(:,1:3,k) = modv(:,1:3);
modv_Qc(:,1:3,k) = modv(:,1:3);
modv_Q(:,1:3,k) = modv(:,1:3);
cf_k = cf(k);
fcName = num2str(cf_k);
if find(fcName == '.')
fcName(fcName == '.') = '_';
end
%%
% Peak delay standard regionalization (for now)
rcpd_k = ray_crosses_pd(:,k);
rtpd_k = retain_pd(:,k);
Apd_k = Apd_i(rtpd_k,rcpd_k);
lpdelta_k = lpdelta(rtpd_k,k);
A_boxes = Apd_k>0;
cts_box = sum(A_boxes,1);
mpd =...
sum(A_boxes.*lpdelta_k,1)'./sum(A_boxes,1)';
mpd(isnan(mpd)) = mean(mpd,'omitnan');
modv_pd(rcpd_k,4,k) = mpd;
modv_pd(rcpd_k,5,k) = cts_box;
%%
% Qc inversion
rcQc_k = ray_crosses_Qc(:,k);
rtQc_k = retain_Qc(:,k);
Ac_k = Ac_i(rtQc_k,rcQc_k);
Qm_k = Qm(rtQc_k,k);
RZZ_k = RZZ(rtQc_k,k);
Wc = Murat_weighting(RZZ_k,QcM);
Gc = Wc*Ac_k;
FName = ['L-curve_Qc_' fcName '_Hz'];
bQm = Wc*Qm_k;
lCurveQc_k = lCurveQc(k);
if isequal(inversionMethod,'Tikhonov')
[mtik0C,residualQc_k,LcQc,tik0_regC]...
=...
Murat_tikhonovQc(outputLCurve,Gc,bQm,lCurveQc_k);
residualQc(1,k) = residualQc_k;
modv_Qc(rcQc_k,4,k) = mtik0C;
elseif isequal(inversionMethod,'Iterative')
disp(['Qc L-curve and cost functions at ', num2str(cf_k), ' Hz.'])
[LcQc, minimizeVectorQm,infoVectorQm,tik0_regC]...
=...
Murat_minimiseCGLS(outputLCurve,Gc,bQm,lCurveQc_k,FName);
residualQc(1,k) = min(infoVectorQm.Rnrm);
modv_Qc(rcQc_k,4,k) = minimizeVectorQm;
elseif isequal(inversionMethod,'Hybrid')
disp(['Qc cost function at ', num2str(cf_k), ' Hz.'])
[LcQc, minimizeVectorQm,infoVectorQm,tik0_regC]...
=...
Murat_minimiseHybrid(outputLCurve,Gc,bQm,lCurveQc_k,FName);
residualQc(1,k) = min(infoVectorQm.Rnrm);
modv_Qc(rcQc_k,4,k) = minimizeVectorQm;
else
error('Unknown inversion method.')
end
saveas(LcQc,fullfile(FPath, FLabel,'Tests',FName));
saveas(LcQc,fullfile(FPath, FLabel,'Tests',FName),'tif');
close(LcQc)
%%
% Q inversion
rcQ_k = ray_crosses_Q(:,k);
rtQ_k = retain_Q(:,k);
A_k = A_i(rtQ_k,rcQ_k);
Q_k = Qm(rtQ_k,k);
luntot_k = luntot(rtQ_k);
time0_k = time0(rtQ_k);
rapsp_k = rapsp(rtQ_k,k);
tCm = tCoda(rtQ_k,k);
[d1, const_Qc_k, ~, ~] = Murat_lsqlinQmean(tCm,tWm,Q_k,...
cf_k,sped,luntot_k,time0_k,rapsp_k);
const_Qc(rtQ_k,k) = const_Qc_k;
lCurveQ_k = lCurveQ(k);
FName = ['L-curve_Q_' fcName '_Hz'];
if isequal(inversionMethod,'Tikhonov')
[mtik0,residualQ_k,LcCN,tik0_reg]...
=...
Murat_tikhonovQ(outputLCurve,A_k,d1,lCurveQ_k,1);
residualQ(:,k) = residualQ_k;
modv_Q(rcQ_k,4,k) = mtik0;
elseif isequal(inversionMethod,'Iterative')
disp(['Q L-curve and cost functions at ', num2str(cf_k), ' Hz.'])
[LcCN, minimizeVectorQ,infoVectorQ,tik0_reg]...
=...
Murat_minimiseCGLS(outputLCurve,A_k,d1,lCurveQ_k,FName);
residualQ(1,k) = min(infoVectorQ.Rnrm);
modv_Q(rcQ_k,4,k) = minimizeVectorQ;
elseif isequal(inversionMethod,'Hybrid')
disp(['Qc cost function at ', num2str(cf_k), ' Hz.'])
[LcCN, minimizeVectorQ,infoVectorQ,tik0_reg]...
=...
Murat_minimiseHybrid(outputLCurve,A_k,d1,lCurveQ_k,FName);
residualQ(1,k) = min(infoVectorQ.Rnrm);
modv_Q(rcQ_k,4,k) = minimizeVectorQ;
end
saveas(LcCN,fullfile(FPath, FLabel,'Tests',FName));
saveas(LcCN,fullfile(FPath, FLabel,'Tests',FName),'tif');
close(LcCN)
%% Checkerboards and spike inputs and checkerboard inversion
% Qc
siz = [nxc nyc nzc];
I = checkerBoard3D(siz,sizea);
[checkInput,spikeInput] =...
Murat_inputTesting(I,spike_o,spike_e,x,y,z);
modv_Qc(checkInput==1,6,k) = latt;
modv_Qc(checkInput==0,6,k) = hatt;
modv_Qc(:,8,k) = mean(Qm_k);
modv_Qc(spikeInput,8,k) = spike_v;
Qc_ch = modv_Qc(rcQc_k,6,k);
re_checkQc = Gc*Qc_ch;
modv_Qc(rcQc_k,7,k) =...
Murat_outputTesting(Gc,re_checkQc,tik0_regC,inversionMethod);
%%
% Q
modv_Q(:,6:8,k) = modv_Qc(:,6:8,k);
Q_ch = modv_Q(rcQ_k,6,k);
re_Q = A_k*Q_ch;
modv_Q(rcQ_k,7,k) =...
Murat_outputTesting(A_k,re_Q,tik0_reg,inversionMethod);
%%
% Inverting spike for Qc and Q at user discretion
if ~isempty(spike_o)
Qc_sp = modv_Qc(rcQc_k,8,k);
re_spikeQc = Gc*Qc_sp;
modv_Qc(rcQc_k,9,k) =...
Murat_outputTesting(Gc,re_spikeQc,tik0_regC,inversionMethod);
Q_sp = modv_Q(rcQ_k,8,k);
re_spikeQ = A_k*Q_sp;
modv_Q(rcQ_k,9,k) =...
Murat_outputTesting(A_k,re_spikeQ,tik0_reg,inversionMethod);
end
%%
% Save peak-delay, Qc, Q
[WE,SN,~] = deg2utm(origin(1),origin(2));
modLLD = Murat_unfoldXYZ(x,y,z/1000);
modUTM = [modLLD(:,1)+WE modLLD(:,2)+SN...
modLLD(:,3)];
modv_pd_k = modv_pd(:,:,k);
modv_pd_k(:,1:3) = modUTM;
FName =...
['peakdelay_' fcName '_UTM_Hz.txt'];
writematrix(modv_pd_k,fullfile(FPath, FLabel, 'TXT', FName));
modv_pd_k(:,1:3) = modLLD;
FName =...
['peakdelay_' fcName '_Degrees_Hz.txt'];
writematrix(modv_pd_k,fullfile(FPath, FLabel, 'TXT', FName));
modv_Qc_k = modv_Qc(:,:,k);
modv_Qc_k(:,1:3) = modUTM;
FName = ['Qc_' fcName '_UTM_Hz.txt'];
writematrix(modv_Qc_k,fullfile(FPath, FLabel, 'TXT', FName));
modv_Qc_k(:,1:3) = modLLD;
FName = ['Qc_' fcName '_Degrees_Hz.txt'];
writematrix(modv_Qc_k,fullfile(FPath, FLabel, 'TXT', FName));
modv_Q_k = modv_Q(:,:,k);
modv_Q_k(:,1:3) = modUTM;
FName = ['Q_' fcName '_UTM_Hz.txt'];
writematrix(modv_Q_k,fullfile(FPath, FLabel, 'TXT', FName));
modv_Q_k(:,1:3) = modLLD;
FName = ['Q_' fcName '_Degrees_Hz.txt'];
writematrix(modv_Q_k,fullfile(FPath, FLabel, 'TXT', FName));
end
%%
% Save in Murat
Murat.data.residualQc = residualQc;
Murat.data.const_Qc = const_Qc;
Murat.data.residualQ = residualQ;
Murat.data.modvPeakDelay = modv_pd;
Murat.data.modvQc = modv_Qc;
Murat.data.modvQ = modv_Q;
writetable(muratHeader,fullfile(FPath, FLabel, 'TXT', 'DataHeaders.xls'));
|
github | LucaDeSiena/MuRAT-master | Murat_selection.m | .m | MuRAT-master/bin/Murat_selection.m | 6,663 | utf_8 | 3670e8259ff2851b2f20fcb2bfbc3719 | %% Seismic attributesare selected and components are considered
function Murat = Murat_selection(Murat)
% SELECTS inputs and data
components = Murat.input.components;
tresholdnoise = Murat.input.tresholdNoise;
modv = Murat.input.modv;
PorS = Murat.input.POrS;
listaSac = Murat.input.listSac;
maPD = Murat.input.maximumPeakDelay;
miPD = Murat.input.minimumPeakDelay;
fT = Murat.input.fitTresholdLinear;
QcM = Murat.input.QcMeasurement;
Apd_i =...
Murat.data.inversionMatrixPeakDelay;
A_i = Murat.data.inversionMatrixQ;
Ac_i = Murat.data.inversionMatrixQc;
peakd = Murat.data.peakDelay;
luntot = Murat.data.totalLengthRay;
tPS = Murat.data.theoreticalTime;
evestaz = Murat.data.locationsDeg;
Qm = Murat.data.inverseQc;
RZZ = Murat.data.uncertaintyQc;
rapsp = Murat.data.energyRatioBodyCoda;
rapspcn = Murat.data.energyRatioCodaNoise;
raysplot = Murat.data.raysPlot;
tCoda = Murat.data.tCoda;
dataL = size(peakd,1);
dataFreq = size(peakd,2);
modvL = size(modv,1);
fitrobust = zeros(2,dataFreq);
ray_crosses_pd = false(modvL,dataFreq);
ray_crosses_Qc = false(modvL,dataFreq);
ray_crosses_Q = false(modvL,dataFreq);
%%
% Warns about problematic data and saves their names and locations
[problemPD,problemQc,problemRZZ,problemQ,~,compMissing,flagWarning]...
=...
Murat_dataWarning(listaSac,tresholdnoise,...
maPD,miPD,fT,peakd,Qm,RZZ,rapspcn,components,0,QcM);
%%
% Selects data in case of multiple components
luntot = luntot(1:components:dataL);
time0 = tPS(1:components:dataL);
tCoda = tCoda(1:components:dataL,:);
evestaz = evestaz(1:components:dataL,:);
raysplot = raysplot(:,:,1:components:dataL);
Ac_i = Ac_i(1:components:dataL,:);
Apd_i = Apd_i(1:components:dataL,:);
A_i = A_i(1:components:dataL,:);
if components > 1
[peakd,Qm,RZZ,rapsp,rapspcn] =...
Murat_components(components,peakd,Qm,RZZ,...
rapsp,rapspcn,compMissing);
end
[~,~,~,~,yesPD,~,~] =...
Murat_dataWarning(listaSac,tresholdnoise,...
maPD,miPD,fT,peakd,Qm,RZZ,rapspcn,components,flagWarning,QcM);
%%
% Operations to decide weight of each data for the solution
% Using Vp/Vs to map max of S waves in the case of P picking
vpvs = sqrt(3);
l10pd = log10(peakd);
if PorS == 2
time0 = time0*vpvs;
t_phase = log10(time0);
elseif PorS == 3
t_phase = log10(time0);
end
%%
% Remove outliers and inversion parameters with little/no sensitivity and
% store the remaining indexes for later
dataLMoreComp = size(peakd,1);
lpdelta = zeros(dataLMoreComp,dataFreq);
retain_pd = false(dataLMoreComp,dataFreq);
retain_Qm = false(dataLMoreComp,dataFreq);
retain_Q = false(dataLMoreComp,dataFreq);
for i = 1:dataFreq
% Peak Delays
yesPD_i = yesPD(:,i);
l10pd_i = l10pd(:,i);
[pab,lpdelta_i,retain_pd_i,ray_crosses_pd_i]...
=...
Murat_retainPeakDelay(t_phase,l10pd_i,yesPD_i,Apd_i);
% Qc
Qm_i = Qm(:,i);
RZZ_i = RZZ(:,i);
[retain_Qm_i,ray_crosses_Qc_i] =...
Murat_retainQc(fT,Qm_i,RZZ_i,Ac_i,QcM);
% Coda-normalization
retain_Q_t = rapspcn(:,i)>=tresholdnoise;
retain_Q_nn = ~isnan(Qm_i);
retain_Q_i = retain_Q_nn & retain_Q_t;
A_retain_Q_i = A_i(retain_Q_i,:);
ray_crosses_Q_i = sum(A_retain_Q_i)~=0;
fitrobust(:,i) = pab;
lpdelta(:,i) = lpdelta_i;
retain_pd(:,i) = retain_pd_i;
ray_crosses_pd(:,i) = ray_crosses_pd_i;
retain_Qm(:,i) = retain_Qm_i;
ray_crosses_Qc(:,i) = ray_crosses_Qc_i;
retain_Q(:,i) = retain_Q_i;
ray_crosses_Q(:,i) = ray_crosses_Q_i;
end
Murat.data.peakDelay = peakd;
Murat.data.totalLengthRay = luntot;
Murat.data.tCoda = tCoda;
Murat.data.locationsDeg = evestaz;
Murat.data.inverseQc = Qm;
Murat.data.uncertaintyQc = RZZ;
Murat.data.problemPD = problemPD;
Murat.data.problemQc = problemQc;
Murat.data.problemRZZ = problemRZZ;
Murat.data.problemQ = problemQ;
Murat.data.energyRatioBodyCoda = rapsp;
Murat.data.energyRatioCodaNoise = rapspcn;
Murat.data.raysPlot = raysplot;
Murat.data.variationPeakDelay = lpdelta;
Murat.data.travelTime = time0;
Murat.data.fitrobust = fitrobust;
Murat.data.retainPeakDelay = retain_pd;
Murat.data.retainQc = retain_Qm;
Murat.data.retainQ = retain_Q;
Murat.data.raysPeakDelay = ray_crosses_pd;
Murat.data.raysQc = ray_crosses_Qc;
Murat.data.raysQ = ray_crosses_Q;
Murat.data.inversionMatrixPeakDelay = Apd_i;
Murat.data.inversionMatrixQc = Ac_i;
Murat.data.inversionMatrixQ = A_i;
end
|
github | LucaDeSiena/MuRAT-master | Murat_data.m | .m | MuRAT-master/bin/Murat_data.m | 9,728 | utf_8 | cc1f113fb803fb0a712364bf20d24da9 | function Murat = Murat_data(Murat)
% MEASURES Qc, peak-delay and Q for each seismic trace located in a folder.
% This code is a collection of functions that do all the necessary.
% Inputs
listSac = Murat.input.listSac;
lengthData = length(listSac);
compon = Murat.input.components;
modv = Murat.input.modv;
lengthParameterModel = length(modv(:,1));
gridStep = [Murat.input.gridStepX/2 ...
Murat.input.gridStepY/2 (modv(2,3) - modv(1,3))/2];
modvQc = [modv(:,1) + gridStep(1)...
modv(:,2)+gridStep(2) modv(:,3)+gridStep(3)];
gridD = Murat.input.gridPropagation;
pvel = Murat.input.pvel;
cf = Murat.input.centralFrequency;
lcf = length(cf);
origin = Murat.input.origin;
originTime = Murat.input.originTime;
PTime = Murat.input.PTime;
STime = Murat.input.STime;
PorS = Murat.input.POrS;
tCm = Murat.input.startLapseTime;
vP = Murat.input.averageVelocityP;
vS = Murat.input.averageVelocityS;
maxtpde = Murat.input.maximumPeakDelay;
tWm = Murat.input.codaWindow;
sped = Murat.input.spectralDecay;
kT = Murat.input.kernelTreshold;
B0 = Murat.input.albedo;
Le1 = Murat.input.extinctionLength;
bodyWindow = Murat.input.bodyWindow;
startNoise = Murat.input.startNoise;
QcM = Murat.input.QcMeasurement;
lapseTimeMethod = Murat.input.lapseTimeMethod;
maxtravel = Murat.input.maxtravel;
% Set up variables to save
locationDeg = zeros(lengthData,6);
locationM = zeros(lengthData,6);
theoreticalTime = zeros(lengthData,1);
totalLengthRay = zeros(lengthData,1);
peakDelay = zeros(lengthData,lcf);
inverseQc = zeros(lengthData,lcf);
uncertaintyQc = zeros(lengthData,lcf);
energyRatioBodyCoda = zeros(lengthData,lcf);
energyRatioCodaNoise = zeros(lengthData,lcf);
raysPlot = zeros(100,5,lengthData);
tCoda = zeros(lengthData,lcf);
inversionMatrixPeakDelay =...
zeros(lengthData,lengthParameterModel);
inversionMatrixQ =...
zeros(lengthData,lengthParameterModel);
inversionMatrixQc =...
zeros(lengthData,lengthParameterModel);
rayCrossing =...
zeros(lengthData,lengthParameterModel);
%=========================================================================
% Count waveforms that must be eliminated because of peak-delay contraints
% on peak delays and coda attenuation.
count_trash = 0;
for i = 1:lengthData
if isequal(mod(i,100),0)
disp(['Waveform number is ', num2str(i)])
end
listSac_i = listSac{i};
% Calculates envelopes
[tempis,sp_i,SAChdr_i,srate_i] = Murat_envelope(cf,listSac_i);
% Set earthquake and stations locations in degrees or meters
[locationDeg_i, locationM_i] =...
Murat_location(origin,SAChdr_i);
locationDeg(i,:) = locationDeg_i;
% Checks direct-wave picking on the trace and outputs it
[cursorPick_i, pktime_i, v_i] = Murat_picking(tempis,...
PTime,STime,PorS,vP,vS,srate_i,listSac_i,SAChdr_i);
% Conditions in case the zero time is missing in the header
[theoreticalTime_i, originTime_i] =...
Murat_originTime(pktime_i,originTime,v_i,locationM_i,SAChdr_i,i);
% Calculates the window where to search for peak delay
cursorPeakDelay_i =...
Murat_peakDelayCheck(tempis,cursorPick_i,maxtpde,srate_i);
% Calculates peak delay time
peakDelay_i =...
Murat_peakDelay(sp_i,cursorPick_i,srate_i,cursorPeakDelay_i);
% Calculates rays for the right component
calculateRays = recognizeComponents(i,compon);
if calculateRays
% All the ray-dependent parameters
[Apd_i, AQ_i, totalLengthRay_i, raysPlot_i, rayCrossing_i]...
=...
Murat_rays(modv,gridD,pvel,locationM_i);
inversionMatrixPeakDelay(i,:) = Apd_i;
inversionMatrixQ(i,:) = AQ_i;
totalLengthRay(i,1) = totalLengthRay_i;
raysPlot(:,:,i) = raysPlot_i;
rayCrossing(i,:) = rayCrossing_i;
end
% Sets the lapse time
[tCoda_i, cursorCodaStart_i,...
cursorCodaEnd_i] =...
Murat_codaCheck(originTime_i,pktime_i,srate_i,tCm,tWm,tempis,...
peakDelay_i,lapseTimeMethod);
if (cursorCodaEnd_i - cursorCodaStart_i) < (tWm*srate_i)-2 || ...
(pktime_i-originTime_i)>maxtravel
locationM(i,:) = locationM_i;
theoreticalTime(i,1) = theoreticalTime_i;
peakDelay(i,:) = NaN;
inverseQc(i,:) = NaN;
uncertaintyQc(i,:) = NaN;
energyRatioBodyCoda(i,:) = NaN;
energyRatioCodaNoise(i,:) = NaN;
tCoda(i,:) = tCoda_i;
count_trash = count_trash +1;
continue
end
% Measures Qc and its uncertainty
[inverseQc_i, uncertaintyQc_i] = Murat_Qc(cf,sped,...
sp_i,cursorCodaStart_i,cursorCodaEnd_i,tCoda_i,srate_i,QcM);
% Decide if you calculate kernels
calculateKernels = recognizeComponents(i,compon);
if calculateKernels
% Calculates kernels
[K_grid, r_grid] =...
Murat_kernels(tCoda_i+tWm/2,locationM_i(1:3),...
locationM_i(4:6),modvQc,vS,kT,B0,Le1,lapseTimeMethod);
% Calculates matrix
AQc_i =...
Murat_codaMatrix(modvQc,K_grid,r_grid,0,[],[]);
inversionMatrixQc(i,:) = AQc_i;
end
% Measures Q
[energyRatioBodyCoda_i,energyRatioCodaNoise_i]=...
Murat_body(bodyWindow,startNoise,srate_i,sp_i,cursorPick_i,...
cursorCodaStart_i,cursorCodaEnd_i);
% Saving
locationM(i,:) = locationM_i;
theoreticalTime(i,1) = theoreticalTime_i;
peakDelay(i,:) = peakDelay_i;
inverseQc(i,:) = inverseQc_i;
uncertaintyQc(i,:) = uncertaintyQc_i;
energyRatioBodyCoda(i,:) = energyRatioBodyCoda_i;
energyRatioCodaNoise(i,:) = energyRatioCodaNoise_i;
tCoda(i,:) = tCoda_i;
end
% Setting up the final data vectors and matrices with checks on values
Murat.data.locationsDeg = locationDeg;
Murat.data.locationsM = locationM;
Murat.data.theoreticalTime = theoreticalTime;
Murat.data.peakDelay = peakDelay;
Murat.data.inversionMatrixPeakDelay = inversionMatrixPeakDelay;
Murat.data.inversionMatrixQ = inversionMatrixQ;
Murat.data.totalLengthRay = totalLengthRay;
Murat.data.raysPlot = raysPlot;
Murat.data.rayCrossing = sum(rayCrossing);
Murat.data.inverseQc = inverseQc;
Murat.data.uncertaintyQc = uncertaintyQc;
Murat.data.inversionMatrixQc = inversionMatrixQc;
Murat.data.energyRatioBodyCoda = energyRatioBodyCoda;
Murat.data.energyRatioCodaNoise = energyRatioCodaNoise;
Murat.data.tCoda = tCoda;
Murat = Murat_selection(Murat);
ratio = count_trash/lengthData*(100);
disp(['Ratio of removed recordings: ', num2str(ratio)])
if ~isempty(Murat.input.declustering)
Murat =...
Murat_declustering(Murat,Murat.input.declustering);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function calculateValue =...
recognizeComponents(index,components)
% LOGICAL to decide if forward model is necessary depending in waveform
% number (index) and number of components.
calculateValue = isequal(components,1) ||...
(isequal(components,2) || isequal(components,3)) &&...
isequal(mod(index,components),1);
|
github | LucaDeSiena/MuRAT-master | Murat_testData.m | .m | MuRAT-master/bin/Murat_testData.m | 3,958 | utf_8 | 0754655d61be06cd08094cda36762c52 | function [muratHeader,flag] =...
Murat_testData(folderPath,originTime,PTime,STime)
% TEST all seismograms in a folder for the input parameters and
% CREATES a file storing the parameters and flagging those missing
%
% Input Parameters:
% folderPath: folder containing the SAC data
% originTime: origin time variable selected by the user
% PTime: P time variable selected by the user
% STime: S time variable selected by the user
%
% Output:
% muratHeader: Murat table showing the necessary parameter
% flag: flags missing optional variables
%
[Names,~] = createsList(folderPath);
lengthData = length(Names);
Origin = cell(lengthData,1);
P = cell(lengthData,1);
S = cell(lengthData,1);
EvLat = cell(lengthData,1);
EvLon = cell(lengthData,1);
EvDepth = cell(lengthData,1);
StLat = cell(lengthData,1);
StLon = cell(lengthData,1);
StElev = cell(lengthData,1);
flag = [];
for i=1:lengthData
listSac_i = Names{i};
[~,SAChdr] = Murat_test(listSac_i,[],8,0,0);
if isequal(eval(originTime),-12345)
Origin{i} = [];
flag = 1;
else
Origin{i} = eval(originTime);
end
if isequal(eval(PTime),-12345)
P{i} = [];
warning(['There is a missing P-value, check ' listSac_i '!']);
else
P{i} = eval(PTime);
end
if isequal(eval(STime),-12345)
S{i} = [];
flag = 2;
else
S{i} = eval(STime);
end
if isequal(SAChdr.event.evla,-12345)
EvLat{i} = [];
warning(['There is a missing event coordinate, check '...
listSac_i '!']);
else
EvLat{i} = SAChdr.event.evla;
end
if isequal(SAChdr.event.evlo,-12345)
EvLon{i} = [];
warning(['There is a missing event coordinate, check '...
listSac_i '!']);
else
EvLon{i} = SAChdr.event.evlo;
end
if isequal(SAChdr.event.evdp,-12345)
EvDepth{i} = [];
warning(['There is a missing event coordinate, check '...
listSac_i '!']);
else
EvDepth{i} = SAChdr.event.evdp;
end
if isequal(SAChdr.station.stla,-12345)
StLat{i} = [];
warning(['There is a missing station coordinate, check '...
listSac_i '!']);
else
StLat{i} = SAChdr.station.stla;
end
if isequal(SAChdr.station.stlo,-12345)
StLon{i} = [];
warning(['There is a missing station coordinate, check '...
listSac_i '!']);
else
StLon{i} = SAChdr.station.stlo;
end
if isequal(SAChdr.station.stel,-12345)
StElev{i} = [];
warning(['There is a missing station coordinate, check '...
listSac_i '!']);
else
StElev{i} = SAChdr.station.stel;
end
end
muratHeader = table(Names,Origin,P,S,EvLat,EvLon,...
EvDepth,StLat,StLon,StElev);
end
%%
function [listWithFolder,listNoFolder]...
= createsList(directory)
% CREATES a list of visible files in a folder, outputs both with and
% without folder
list = dir(directory);
list = list(~startsWith({list.name}, '.'));
listWithFolder = fullfile({list.folder},{list.name})';
listNoFolder = {list.name}';
end |
github | LucaDeSiena/MuRAT-master | Murat_plot.m | .m | MuRAT-master/bin/Murat_plot.m | 23,641 | utf_8 | 2f3db3d30d35e77bfd856cec3e0ebb1f | %% MURAT_PLOT Creates files for visualization in Matlab and Paraview
function Murat = Murat_plot(Murat)
%%
% Importing all the necessary inputs and data for plotting
FLabel = Murat.input.label;
origin = Murat.input.origin;
ending = Murat.input.end;
x = Murat.input.x;
y = Murat.input.y;
z = Murat.input.z;
sections = Murat.input.sections;
plotV = Murat.input.modvPlot;
cf = Murat.input.centralFrequency;
vS = Murat.input.averageVelocityS;
tWm = Murat.input.codaWindow;
kT = Murat.input.tresholdNoise;
B0 = Murat.input.albedo;
Le1 = Murat.input.extinctionLength;
QcM = Murat.input.QcMeasurement;
sped = Murat.input.spectralDecay;
lapseTimeMethod = Murat.input.lapseTimeMethod;
modvQc = Murat.input.modv;
stepgX = (modvQc(2,1) - modvQc(1,1))/2;
stepgY = (modvQc(2,2) - modvQc(1,2))/2;
stepgZ = (modvQc(2,3) - modvQc(1,3))/2;
modvQc(:,1) = modvQc(:,1) + stepgX;
modvQc(:,2) = modvQc(:,2) + stepgY;
modvQc(:,3) = modvQc(:,3) + stepgZ;
Qm = Murat.data.inverseQc;
time0 = Murat.data.travelTime;
retainPeakDelay = Murat.data.retainPeakDelay;
retainQc = Murat.data.retainQc;
retainQ = Murat.data.retainQ;
ray_crosses_pd = Murat.data.raysPeakDelay;
ray_crosses_Qc = Murat.data.raysQc;
ray_crosses_Q = Murat.data.raysQ;
fitrobust = Murat.data.fitrobust;
peakData = Murat.data.peakDelay;
luntot = Murat.data.totalLengthRay;
rma = Murat.data.raysPlot;
modv_pd = Murat.data.modvPeakDelay;
modv_Qc = Murat.data.modvQc;
modv_Q = Murat.data.modvQ;
evestazDegrees = Murat.data.locationsDeg;
energyRatio = Murat.data.energyRatioBodyCoda;
codaNoiseRatio = Murat.data.energyRatioCodaNoise;
Ac_i = Murat.data.inversionMatrixQc;
RZZ = Murat.data.uncertaintyQc;
A_i = Murat.data.inversionMatrixQ;
residualQc = Murat.data.residualQc;
residualQ = Murat.data.residualQ;
locationM = Murat.data.locationsM;
tCoda = Murat.data.tCoda;
rapsp = Murat.data.energyRatioBodyCoda;
FPath = './';
sizeTitle = 18;
lMF = size(ray_crosses_pd);
sections(3) = sections(3)/1000;
%% PLOTS - coverage and sensitivity
% Declustering is done before any frequency analysis, here we show the 2D
% rays before and after
if Murat.input.declustering > 0
locDegOriginal = Murat.data.locDegOriginal;
FName_Cluster = 'Clustering';
clustering = Murat_imageDeclustering(...
locDegOriginal,evestazDegrees,origin,ending,FName_Cluster);
storeFolder = 'RaysKernels';
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_Cluster);
saveas(clustering,pathFolder,'tif');
close(clustering)
end
evestaz =...
[evestazDegrees(:,1:2) -evestazDegrees(:,3)/1000 ...
evestazDegrees(:,4:5) evestazDegrees(:,6)/1000];
averageQcFrequency = zeros(2,lMF(2));
for k = 1:lMF(2)
% Murat_plot starts plotting the ray distribution if asked by the user.
% It stores the files in the corresponding folder.
storeFolder = 'RaysKernels';
cf_k = cf(k);
fcName = num2str(cf_k);
if find(fcName == '.')
fcName(fcName == '.') = '_';
end
rtpdk = retainPeakDelay(:,k);
rtQk = retainQ(:,k);
rcQk = ray_crosses_Q(:,k);
rtQck = retainQc(:,k);
rcQck = ray_crosses_Qc(:,k);
%%
% The rays are visualized for different techniques, starting with the peak delay
FName_peakDelay = ['Rays_PeakDelay_' fcName '_Hz'];
rma_pd = rma(:,2:4,rtpdk)/1000;
evestaz_pd = evestaz(rtpdk,:);
rays_peakDelay = Murat_imageRays(rma_pd,origin,...
ending,evestaz_pd,x,y,z,FName_peakDelay);
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_peakDelay);
saveas(rays_peakDelay,pathFolder,'tif');
close(rays_peakDelay)
%%
% The next figure shows the rays for the total attenuation (Q)
FName_Q = ['Rays_Q_' fcName '_Hz'];
rma_Q = rma(:,2:4,rtQk)/1000;
evestaz_Q = evestaz(rtQk,:);
rays_Q =...
Murat_imageRays(rma_Q,origin,ending,evestaz_Q,x,y,z,FName_Q);
pathFolder =...
fullfile(FPath, FLabel, storeFolder, FName_Q);
saveas(rays_Q,pathFolder,'tif');
close(rays_Q)
%%
% The next figure checks the sensitivity of coda attenuation
% measurements. The code creates figures that show sections in the
% sensitivity kernels. The left panel shows the sensitivity kernel in
% the full space while the rigth panel shows the normalized
% kernel in the inversion grid.
FName_Qc = ['Kernel_Qc' fcName '_Hz'];
kernels = figure('Name',FName_Qc,...
'NumberTitle','off','Position',[20,400,1200,1000],'visible','off');
% Calculates kernels
[K_grid, r_grid] =...
Murat_kernels(tCoda(1)+tWm/2,locationM(1,1:3),locationM(1,4:6),...
modvQc,vS,kT,B0,Le1,lapseTimeMethod);
Murat_codaMatrix(modvQc,K_grid,r_grid,1,origin,sections);
pathFolder =...
fullfile(FPath, FLabel, storeFolder, FName_Qc);
Murat_saveFigures_2panels(kernels,pathFolder);
%% Plot - Tests
% In this section Murat_plot makes checks on the three parameters.
% These plots are always visualised. They check that:
% (1) Qc is constant with ray length - also computes weighted average;
% (2) peak delays increase with travel time;
% (3) amplitude ratios decay with hypocentral distance.
% These plots are used to select measurements and understand how well
% they follow the assumptions.
storeFolder = 'Tests';
Qm_k = Qm(rtQck,k);
RZZ_k = RZZ(rtQck,k);
residualQc_k = residualQc(k);
luntot_Qc = luntot(rtQck)/1000;
Ac = Ac_i(rtQck,rcQck);
averageQcFrequency(1,k) = sum(RZZ_k.*Qm_k)/sum(RZZ_k);
averageQcFrequency(2,k) = std(Qm_k);
Qc_title = ['Qc check ' fcName ' Hz'];
Qc_analysis = Murat_imageCheckQc(Qm_k,RZZ_k,...
residualQc_k,luntot_Qc,Ac,sizeTitle,Qc_title,QcM);
saveas(Qc_analysis, fullfile(FPath,FLabel,storeFolder,...
['Qc_analysis_' fcName '_Hz']),'tif');
saveas(Qc_analysis, fullfile(FPath,FLabel,storeFolder,...
['Qc_analysis_' fcName '_Hz']));
close(Qc_analysis)
%%
% Then it shows the peak delay relative to the travel time.
peakData_k = peakData(rtpdk,k);
fitrobust_k = fitrobust(:,k);
time0PD = time0(rtpdk);
pd_title = ['Peak Delay check ' fcName ' Hz'];
pd_analysis = Murat_imageCheckPeakDelay(...
time0PD,fitrobust_k,peakData_k,sizeTitle,pd_title);
saveas(pd_analysis, fullfile(FPath,FLabel,storeFolder,...
['PD_analysis_' fcName '_Hz']),'tif');
saveas(pd_analysis, fullfile(FPath,FLabel,storeFolder,...
['PD_analysis_' fcName '_Hz']));
close(pd_analysis)
%%
% Then it plots first the logarithm of the energy ratio versus travel
% time.
energyRatio_k = energyRatio(rtQk,k);
residualQ_k = residualQ(k);
Edirect_k =...
energyRatio_k./codaNoiseRatio(rtQk,k);
A_k = A_i(rtQk,rcQk);
luntot_k = luntot(rtQk);
time0_k = time0(rtQk);
rapsp_k = rapsp(rtQk,k);
tCm = tCoda(rtQk,k);
Q_k = Qm(rtQk,k);
CN_title =...
['Coda Normalization check ' fcName ' Hz'];
[d1, ~,spreadAverageQ, equationQ]...
=...
Murat_lsqlinQmean(tCm,tWm,Q_k,cf_k,sped,luntot_k,time0_k,rapsp_k);
CN_analysis =...
Murat_imageCheckCN(equationQ,residualQ_k,d1,spreadAverageQ,...
luntot_k,time0_k,energyRatio_k,A_k,Edirect_k,CN_title);
saveas(CN_analysis, fullfile(FPath,FLabel,storeFolder,...
['CN_analysis_' fcName '_Hz']),'tif');
saveas(CN_analysis, fullfile(FPath,FLabel,storeFolder,...
['CN_analysis_' fcName '_Hz']));
close(CN_analysis)
%% PLOT - RESULTS
% Set up matrices. The points are set to the upper SW vertices to
% work with the function "slice". All stored in the sub-folder.
modv_pd_k = modv_pd(:,:,k);
modv_Qc_k = modv_Qc(:,:,k);
modv_Q_k = modv_Q(:,:,k);
[X,Y,Z1,mPD] = Murat_fold(x,y,z,modv_pd_k(:,4));
[~,~,~,PD_cts] = Murat_fold(x,y,z,modv_pd_k(:,5));
[~,~,~,mQc] = Murat_fold(x,y,z,modv_Qc_k(:,4));
[~,~,~,mQ] = Murat_fold(x,y,z,modv_Q_k(:,4));
Z = Z1/1000;
evestaz_Qc = evestaz(rtQck,:);
%%
% Peak delays results, using interpolation defined by 'divi'.
divi = 5;
storeFolder = 'Results/PeakDelay';
FName_PDMap = ['Peak-Delay-3D_' fcName '_Hz'];
peakDelaymap = Murat_image3D(X,Y,Z,mPD,...
redblue,sections,evestaz_pd,x,y,z,divi,FName_PDMap);
title('Log. peak-delay variations',...
'FontSize',sizeTitle,'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath, FLabel, storeFolder, FName_PDMap);
Murat_saveFigures(peakDelaymap,pathFolder);
%%
% Plots peak delays only keeping cells with more than 'factor'% of data
factor = 5;
keep_bins =...
PD_cts > ((max(PD_cts(:))/100)*factor);
mPD_red = mPD.*keep_bins;
FName_PDMap =...
['Peak-Delay-3D_' fcName '_Hz_',num2str(factor),'_perc'];
[peakDelaymap_red,pd_inter,~,~,~,Xi,Yi,Zi]...
= Murat_image3D(X,Y,Z,mPD_red,...
redblue,sections,evestaz_pd,x,y,z,divi,FName_PDMap);
title('Peak-delay variations','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath, FLabel, storeFolder, FName_PDMap);
Murat_saveFigures(peakDelaymap_red,pathFolder);
% interpolated for the parameter map
interp_modv_pd_k = Murat_unfold(Xi,Yi,Zi,pd_inter);
%%
% Qc results
storeFolder = 'Results/Qc';
FName_QcMap = ['Qc-3D_' fcName '_Hz'];
[Qcmap,qc_inter,xi,yi,zi,Xi,Yi,Zi]...
= Murat_image3D(X,Y,Z,mQc,...
turbo,sections,evestaz_Qc,x,y,z,divi,FName_QcMap);
title('Coda attenuation',...
'FontSize',sizeTitle,'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_QcMap);
Murat_saveFigures(Qcmap,pathFolder);
% interpolated for the parameter map
interp_modv_qc_k = Murat_unfold(Xi,Yi,Zi,qc_inter);
%%
% Q results
storeFolder = 'Results/Q';
FName_QMap = ['Q-3D_' fcName '_Hz'];
Qmap = Murat_image3D(X,Y,Z,mQ,...
hot,sections,evestaz_Q,x,y,z,divi,FName_QMap);
title('Total attenuation variations','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_QMap);
Murat_saveFigures(Qmap,pathFolder);
%% PLOT - CHECKERBOARDS
% In this section Murat_plot shows the checkerboard tests
% for Q and Qc.
[~,~,~,check_inputQc] = Murat_fold(x,y,z,modv_Qc_k(:,6));
[~,~,~,check_outputQc] = Murat_fold(x,y,z,modv_Qc_k(:,7));
[~,~,~,check_inputQ] = Murat_fold(x,y,z,modv_Qc_k(:,6));
[~,~,~,check_outputQ] = Murat_fold(x,y,z,modv_Q_k(:,7));
%%
% Checkerboard Qc: Input and Output
storeFolder = 'Checkerboard/Qc';
FName_QcCheck = ['Qc-Checkerboard_' fcName '_Hz'];
Qc_check = figure('Name',FName_QcCheck,...
'NumberTitle','off','Position',[20,400,2000,1000],'visible','off');
subplot(1,2,1)
Murat_image3D_2panels(X,Y,Z,check_inputQc,...
'bone',sections,evestaz_Qc,x,y,z);
title('Input checkerboard Qc','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
subplot(1,2,2)
Murat_image3D_2panels(X,Y,Z,check_outputQc,...
'bone',sections,evestaz_Qc,x,y,z);
title('Output checkerboard Qc','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_QcCheck);
Murat_saveFigures_2panels(Qc_check,pathFolder);
%%
%Checkerboard Q: Input and Output
storeFolder = 'Checkerboard/Q';
FName_QCheck = ['Q-Checkerboard_' fcName '_Hz'];
Q_check = figure('Name',FName_QCheck,...
'NumberTitle','off','Position',[20,400,2000,1000],'visible','off');
subplot(1,2,1)
Murat_image3D_2panels(X,Y,Z,check_inputQ,...
'bone',sections,evestaz_Q,x,y,z);
title('Input checkerboard Q','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
subplot(1,2,2)
Murat_image3D_2panels(X,Y,Z,check_outputQ,...
'bone',sections,evestaz_Q,x,y,z);
title('Output checkerboard Q',...
'FontSize',sizeTitle,'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_QCheck);
Murat_saveFigures_2panels(Q_check,pathFolder);
%% PLOT - SPIKES
% In this section Murat_plot shows input and output of the spike tests
% for Q and Qc.
[~,~,~,spike_inputQc] = Murat_fold(x,y,z,modv_Qc_k(:,8));
[~,~,~,spike_outputQc] = Murat_fold(x,y,z,modv_Qc_k(:,9));
[~,~,~,spike_inputQ] = Murat_fold(x,y,z,modv_Qc_k(:,8));
[~,~,~,spike_outputQ] = Murat_fold(x,y,z,modv_Q_k(:,9));
%%
% Spike Qc: Input and Output
storeFolder = 'Spike/Qc';
FName_QcSpike = ['Qc-Spike_' fcName '_Hz'];
Qc_spike = figure('Name',FName_QcSpike,...
'NumberTitle','off','Position',[20,400,2000,1000],'visible','off');
subplot(1,2,1)
Murat_image3D_2panels(X,Y,Z,spike_inputQc,...
winter,sections,evestaz_Qc,x,y,z);
title('Input spike Qc','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
subplot(1,2,2)
Murat_image3D_2panels(X,Y,Z,spike_outputQc,...
winter,sections,evestaz_Qc,x,y,z);
title('Output spike Qc','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_QcSpike);
Murat_saveFigures_2panels(Qc_spike,pathFolder);
%%
% Spike Q: Input and Output
storeFolder = 'Spike/Q';
FName_QSpike = ['Q-Spike_' fcName '_Hz'];
Q_spike = figure('Name',FName_QSpike,...
'NumberTitle','off','Position',[20,400,2000,1000],'visible','off');
subplot(1,2,1)
Murat_image3D_2panels(X,Y,Z,spike_inputQ,hot,sections,evestaz_Q,x,y,z);
title('Input spike Q','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
subplot(1,2,2)
Murat_image3D_2panels(X,Y,Z,spike_outputQ,...
hot,sections,evestaz_Q,x,y,z);
title('Output spike Q','FontSize',sizeTitle,...
'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_QSpike);
Murat_saveFigures_2panels(Q_spike,pathFolder);
%% PARAMETER PLOT
% The final figure is the parameter plot separation.
% First Qc and Peak delay are separated in 4 quadrants.
% The second part produces the spatial plot, setting each node to the
% corresponding color. The four options are: (1) high for both (red);
% (2) low for both (green); (3) high for peak delays only (cyan);
% (4) high for inverse Qc only (orange).
storeFolder = 'Results/Parameter';
%%
% Define all the parameters for imaging
FName_Parameters =...
['Parameter_space_variations_' fcName '_Hz'];
[param_plot,~,~] =...
Murat_imageParameters(x,y,z,modv_pd_k,modv_Qc_k,sizeTitle);
saveas(param_plot,fullfile(FPath,FLabel,storeFolder,FName_Parameters));
close(param_plot)
% use interpolated peakdelay and Qc
zi = (zi*1000)';
[~,par_inter,para_map_inter] = Murat_imageParameters(xi',yi',...
zi,interp_modv_pd_k,interp_modv_qc_k,sizeTitle);
%%
% Imaging the parameters in 3D
FName_PMap = ['Parameter-Map_' fcName '_Hz'];
[ParaMap,para_map] =...
Murat_imageParametersMaps(par_inter,para_map_inter,xi',yi',zi,...
Xi,Yi,Zi,evestaz_Qc,sections,sizeTitle,FName_PMap);
[WE,SN,~] = deg2utm(origin(1),origin(2));
modLLD = Murat_unfoldXYZ(xi,yi,zi/1000);
modUTM = [modLLD(:,1)+WE modLLD(:,2)+SN...
modLLD(:,3)];
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_PMap);
Murat_saveFigures(ParaMap,pathFolder);
FName =...
['parameterMap_' fcName '_UTM_Hz.txt'];
writematrix(para_map,fullfile(FPath, FLabel, 'TXT', FName));
para_map(:,1:3) = modUTM;
FName =...
['parameterMap_' fcName '_Degrees_Hz.txt'];
writematrix(para_map,fullfile(FPath, FLabel, 'TXT', FName));
%% SAVE all results as VTK for visualization in PARAVIEW
% Converting Lon/Lat to km for paraview visualization with ndgrid
storeFolder = 'VTK';
[WE_origin, SN_origin] = deg2utm(origin(2),origin(1));
x_origin = x - origin(2);
y_origin = y - origin(1);
UTM_WE = WE_origin + deg2km(x_origin)*1000;
UTM_SN = SN_origin + deg2km(y_origin)*1000;
[X_UTM,Y_UTM,~] = meshgrid(UTM_WE,UTM_SN,z);
%%
% Writes the four models to vtk
vtkwrite(fullfile(FPath, FLabel,storeFolder,[FName_PDMap '.vtk']),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Peak_delay',mPD)
vtkwrite(fullfile(FPath, FLabel,storeFolder,[FName_QcMap '.vtk']),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Qc',mQc)
vtkwrite(fullfile(FPath, FLabel,storeFolder,[FName_QMap '.vtk']),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Q',mQ)
%%
% Write the input-output checkerboard
vtkwrite(fullfile(FPath, FLabel,storeFolder,[FName_QcCheck '.vtk']),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Check_Qc',...
check_outputQc)
vtkwrite(fullfile(FPath, FLabel,storeFolder,[FName_QCheck '.vtk']),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Check_Q',...
check_outputQ)
%%
% Writes the input-output spikes
vtkwrite(fullfile(FPath, FLabel,storeFolder,[FName_QSpike '.vtk']),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Spike_Qc',...
spike_outputQc)
vtkwrite(fullfile(FPath, FLabel,storeFolder,[FName_QSpike '.vtk']),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Spike_Q',...
spike_outputQ)
end
%%
% Also showing the velocity model in case it is available, only once
vtkwrite(fullfile(FPath, FLabel,storeFolder,'Velocity_model.vtk'),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','V',plotV)
vtkwrite(fullfile(FPath, FLabel,storeFolder,'Input_checkerboards.vtk'),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Input_check',...
check_inputQc)
vtkwrite(fullfile(FPath, FLabel,storeFolder,'Input_spikes.vtk'),...
'structured_grid',X_UTM,Y_UTM,Z1,'scalars','Input_spikes',...
spike_inputQc)
%%
% Final figures are the velocity model and Qc/frequency relation
storeFolder = 'Tests';
if Murat.input.availableVelocity == 1
FName_Vimage = 'Velocity_model';
Vimage = Murat_image3D(X,Y,Z,plotV,...
inferno,sections,evestaz_Q,x,y,z,divi,FName_Vimage);
title('Velocity Model',...
'FontSize',sizeTitle,'FontWeight','bold','Color','k');
pathFolder =...
fullfile(FPath,FLabel,storeFolder,FName_Vimage);
saveas(Vimage,pathFolder);
close(Vimage)
end
Murat.data.averageQcFrequency = averageQcFrequency;
Qcf_title = 'Qc vs Frequency';
QcFrequency = Murat_imageQcFrequency(cf,...
averageQcFrequency,sizeTitle,Qcf_title);
FName = 'Qc_vs_frequency';
saveas(QcFrequency, fullfile(FPath,FLabel,storeFolder,FName),'tif');
close all
|
github | LucaDeSiena/MuRAT-master | Murat_checks.m | .m | MuRAT-master/bin/Murat_checks.m | 4,102 | utf_8 | 68fdc004d6d957ab6590dbec71161ed5 | % ADDITIONAL input variables that are not set by the user.
function Murat = Murat_checks(Murat)
% INPUTS
dataDirectory = ['./' Murat.input.dataDirectory];
PTime = ['SAChdr.times.' Murat.input.PTime];
PorS = Murat.input.POrS;
origin = Murat.input.origin;
ending = Murat.input.end;
nLat = Murat.input.gridLat;
nLong = Murat.input.gridLong;
nzc = Murat.input.gridZ;
availableVelocity = Murat.input.availableVelocity;
velocityModel = ['velocity_models/',Murat.input.namev];
if isempty(Murat.input.originTime)
originTime = 'SAChdr.times.o';
else
originTime =...
['SAChdr.times.' Murat.input.originTime];
end
if isempty(Murat.input.STime)
STime = 'SAChdr.times.t0';
else
STime =...
['SAChdr.times.' Murat.input.STime];
end
Murat.input.originTime = originTime;
Murat.input.PTime = PTime;
Murat.input.STime = STime;
if exist('./temp','dir')==7
delete('./temp/*')
else
mkdir('./temp')
end
% Checking data
[Murat.input.listSac,~] = createsList([dataDirectory '/*.sac']);
[Murat.input.header,flag] =...
Murat_testData(dataDirectory,originTime,PTime,STime);
if isequal(flag,1)
warning('Missing origin times.')
end
if isequal(flag,2)
warning('Missing S-wave times.')
end
%% VELOCITY MODELS: ORIGINAL, INVERSION, and PROPAGATION
% Save x,y,z in degrees switching as longitude comes second
% Find distance and azimuth to change in meters - requires longitude first
dist_x = deg2km(ending(2)-origin(2))*1000;
dist_y = deg2km(ending(1)-origin(1))*1000;
% Coordinates of inversion points in meters
xM = linspace(0,dist_x,nLong)';
yM = linspace(0,dist_y,nLat)';
zM = linspace(origin(3),ending(3),nzc)';
modvXYZ = Murat_unfoldXYZ(xM,yM,zM);
Murat.input.x = linspace(origin(2),ending(2),nLong)';
Murat.input.y = linspace(origin(1),ending(1),nLat)';
Murat.input.z = linspace(origin(3),ending(3),nzc)';
Murat.input.gridStepX = xM(2)-xM(1);
Murat.input.gridStepY = yM(2)-yM(1);
modvOriginal = load(velocityModel);
if availableVelocity == 0
gridPropagation.x = xM';
gridPropagation.y = yM';
gridPropagation.z = zM';
[modv,pvel] =...
Murat_modv1D(modvXYZ,modvOriginal,PorS);
Murat.input.modv = modv;
Murat.input.modvp = modv;
Murat.input.modvPlot = [];
elseif availableVelocity == 1
[modvP,modvI,modvIP,pvel] =...
Murat_modv3D(modvXYZ,modvOriginal,origin,0);
gridPropagation.x = unique(modvP(:,1));
gridPropagation.y = unique(modvP(:,2));
gridPropagation.z = sort(unique(modvP(:,3)),'descend');
Murat.input.modv = modvI;
Murat.input.modvp = modvP(:,1:4);
Murat.input.modvPlot = modvIP;
end
Murat.input.gridPropagation = gridPropagation;
Murat.input.pvel = pvel;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [listWithFolder,listNoFolder]...
= createsList(directory)
% CREATES a list of visible files in a folder, outputs both with and
% without folder
list = dir(directory);
list = list(~startsWith({list.name}, '.'));
listWithFolder = fullfile({list.folder},{list.name})';
listNoFolder = {list.name}';
|
github | LucaDeSiena/MuRAT-master | checkerBoard3D.m | .m | MuRAT-master/Utilities_Matlab/GIBBON/checkerBoard3D.m | 1,470 | utf_8 | 635da4564067b7f09920be527a385cc1 | function M=checkerBoard3D(varargin)
% function M=checkerBoard3D(siz)
% ------------------------------------------------------------------------
% This function creates a checkboard image of the size siz whereby elements
% are either black (0) or white (1). The first element is white.
% example: siz=[12 12 6]; blockSize=2;
%Block size in pixel units
% Kevin Mattheus Moerman
% [email protected]
% 2008/08/15
% 2018/12/10 Added checkboard block size input
% ------------------------------------------------------------------------
%% Parse input
switch nargin
case 1
siz=varargin{1};
blockSize=1;
case 2
siz=varargin{1};
blockSize=varargin{2};
end
% if ~isrounded(blockSize) || blockSize<1
% error('Block size should be positive integer');
% end
%Coping with 1D or 2D input
if numel(siz)==2
siz(3)=1;
elseif numel(siz)==1
siz(2:3)=[1 1];
end
%%
if blockSize==1
[I,J,K]=ndgrid(1:1:siz(1),1:1:siz(2),1:1:siz(3));
else
[I,J,K]=ndgrid(indexRange(blockSize,siz(1)),indexRange(blockSize,siz(2)),indexRange(blockSize,siz(3)));
end
logic_ij=((iseven(I)| iseven(J)) & ((iseven(I)~=iseven(J))));
M=false(siz);
M(iseven(K))=logic_ij(iseven(K));
M(~iseven(K))=~logic_ij(~iseven(K));
end
%%
function i=indexRange(blockSize,s)
i=repmat(1:blockSize:s,blockSize,1);
i=i(:);
if numel(i)<s
ii=i;
i=siz(1)*ones(1,s);
i(1:num_i)=ii;
else
i=i(1:s);
end
[~,~,i]=unique(i);
end |
github | LucaDeSiena/MuRAT-master | inpaintn.m | .m | MuRAT-master/Utilities_Matlab/GIBBON/inpaintn.m | 11,643 | utf_8 | e056d112de8a3d4da94ffedf055d72b2 | function y = inpaintn(x,n,y0,m)
% INPAINTN Inpaint over missing data in N-D array
% Y = INPAINTN(X) replaces the missing data in X by extra/interpolating
% the non-missing elements. The non finite values (NaN or Inf) in X are
% considered as missing data. X can be any N-D array.
%
% INPAINTN (no input/output argument) runs the following 3-D example.
%
% Important note:
% --------------
% INPAINTN uses an iterative process baased on DCT and IDCT.
% Y = INPAINTN(X,N) uses N iterations. By default, N = 100. If you
% estimate that INPAINTN did not totally converge, increase N:
% Y = INPAINTN(X,1000)
%
% Y = INPAINTN(X,N,Y0) uses Y0 as initial guess. This could be useful if
% you want to run the process a second time or if you have a GOOD guess
% of the final result. By default, INPAINTN makes a nearest neighbor
% interpolation (by using BWDIST) to obtain a rough guess.
%
% References (please refer to the two following references)
% ----------
% 1) Garcia D, Robust smoothing of gridded data in one and higher
% dimensions with missing values. Computational Statistics & Data
% Analysis, 2010;54:1167-1178.
% <a
% href="matlab:web('http://www.biomecardio.com/publis/csda10.pdf')">download PDF</a>
% 2) Wang G, Garcia D et al. A three-dimensional gap filling method for
% large geophysical datasets: Application to global satellite soil
% moisture observations. Environ Modell Softw, 2012;30:139-142.
% <a
% href="matlab:web('http://www.biomecardio.com/publis/envirmodellsoftw12.pdf')">download PDF</a>
%
% Examples
% --------
%
% %% ---- RGB image ---- %%
% onion = imread('onion.png');
% I = randperm(numel(onion));
% onionNaN = double(onion); onionNaN(I(1:round(numel(I)*0.5))) = NaN;
% subplot(211), imshow(uint8(onionNaN)), title('Corrupted image - 50%')
% for k=1:3, onion(:,:,k) = inpaintn(onionNaN(:,:,k)); end
% subplot(212), imshow(uint8(onion)), title('Inpainted image')
%
% %% ---- 2-D data ---- %%
% n = 256;
% y0 = peaks(n);
% y = y0;
% I = randperm(n^2);
% y(I(1:n^2*0.5)) = NaN; % lose 1/2 of data
% y(40:90,140:190) = NaN; % create a hole
% z = inpaintn(y,200); % inpaint data
% subplot(2,2,1:2), imagesc(y), axis equal off
% title('Corrupted data')
% subplot(223), imagesc(z), axis equal off
% title('Recovered data ...')
% subplot(224), imagesc(y0), axis equal off
% title('... compared with original data')
%
% %% ---- 3-D data ---- %%
% load wind
% xmin = min(x(:)); xmax = max(x(:));
% zmin = min(z(:)); ymax = max(y(:));
% %-- wind velocity
% vel0 = interp3(sqrt(u.^2+v.^2+w.^2),1,'cubic');
% x = interp3(x,1); y = interp3(y,1); z = interp3(z,1);
% %-- remove randomly 90% of the data
% I = randperm(numel(vel0));
% velNaN = vel0;
% velNaN(I(1:round(numel(I)*.9))) = NaN;
% %-- inpaint using INPAINTN
% vel = inpaintn(velNaN);
% %-- display the results
% subplot(221), imagesc(velNaN(:,:,15)), axis equal off
% title('Corrupted plane, z = 15')
% subplot(222), imagesc(vel(:,:,15)), axis equal off
% title('Reconstructed plane, z = 15')
% subplot(223)
% hsurfaces = slice(x,y,z,vel0,[xmin,100,xmax],ymax,zmin);
% set(hsurfaces,'FaceColor','interp','EdgeColor','none')
% hcont = contourslice(x,y,z,vel0,[xmin,100,xmax],ymax,zmin);
% set(hcont,'EdgeColor',[.7,.7,.7],'LineWidth',.5)
% view(3), daspect([2,2,1]), axis tight
% title('Original data compared with...')
% subplot(224)
% hsurfaces = slice(x,y,z,vel,[xmin,100,xmax],ymax,zmin);
% set(hsurfaces,'FaceColor','interp','EdgeColor','none')
% hcont = contourslice(x,y,z,vel,[xmin,100,xmax],ymax,zmin);
% set(hcont,'EdgeColor',[.7,.7,.7],'LineWidth',.5)
% view(3), daspect([2,2,1]), axis tight
% title('... reconstructed data')
%
% %% --- 4-D data --- %%
% [x1,x2,x3,x4] = ndgrid(-2:0.2:2);
% z0 = x2.*exp(-x1.^2-x2.^2-x3.^2-x4.^2);
% I = randperm(numel(z0));
% % remove 50% of the data
% zNaN = z0; zNaN(I(1:round(numel(I)*.5))) = NaN;
% % reconstruct the data using INPAINTN
% z = inpaintn(zNaN);
% % display the results (for x4 = 0)
% subplot(211)
% zNaN(isnan(zNaN)) = 0.5;
% slice(x2(:,:,:,1),x1(:,:,:,1),x3(:,:,:,1),zNaN(:,:,:,11),...
% [-1.2 0.8 2],2,[-2 0.2])
% title('Corrupt data, x4 = 0')
% subplot(212)
% slice(x2(:,:,:,1),x1(:,:,:,1),x3(:,:,:,1),z(:,:,:,11),...
% [-1.2 0.8 2],2,[-2 0.2])
% title('Reconstructed data')
%
% See also SMOOTHN, GRIDDATAN
%
% -- Damien Garcia -- 2010/06, last update 2017/08
% website: <a
% href="matlab:web('http://www.biomecardio.com/en')">www.BiomeCardio.com</a>
if nargin==0&&nargout==0, RunTheExample, return, end
class0 = class(x);
x = double(x);
if nargin==1 || isempty(n), n = 100; end
sizx = size(x);
d = ndims(x);
Lambda = zeros(sizx);
for i = 1:d
siz0 = ones(1,d);
siz0(i) = sizx(i);
Lambda = bsxfun(@plus,Lambda,...
cos(pi*(reshape(1:sizx(i),siz0)-1)/sizx(i)));
end
Lambda = 2*(d-Lambda);
% Initial condition
W = isfinite(x);
if nargin==3 && ~isempty(y0)
y = y0;
s0 = 3; % note: s = 10^s0
else
if any(~W(:))
[y,s0] = InitialGuess(x,isfinite(x));
else
y = x;
return
end
end
x(~W) = 0;
if isempty(n) || n<=0, n = 100; end
% Smoothness parameters: from high to negligible values
s = logspace(s0,-6,n);
RF = 2; % relaxation factor
if nargin<4 || isempty(m), m = 2; end
Lambda = Lambda.^m;
h = waitbar(0,'Inpainting...');
for i = 1:n
Gamma = 1./(1+s(i)*Lambda);
y = RF*idctn(Gamma.*dctn(W.*(x-y)+y)) + (1-RF)*y;
waitbar(i/n,h)
end
close(h)
y(W) = x(W);
y = cast(y,class0);
end
%% Initial Guess
function [z,s0] = InitialGuess(y,I)
if license('test','image_toolbox')
%-- nearest neighbor interpolation
[~,L] = bwdist(I);
z = y;
z(~I) = y(L(~I));
s0 = 3; % note: s = 10^s0
else
warning('MATLAB:inpaintn:InitialGuess',...
['BWDIST (Image Processing Toolbox) does not exist. ',...
'The initial guess may not be optimal; additional',...
' iterations can thus be required to ensure complete',...
' convergence. Increase N value if necessary.'])
z = y;
z(~I) = mean(y(I));
s0 = 6; % note: s = 10^s0
end
end
%% Example (3-D)
function RunTheExample
load wind %#ok
xmin = min(x(:)); xmax = max(x(:)); %#ok
zmin = min(z(:)); ymax = max(y(:)); %#ok
%-- wind velocity
vel0 = interp3(sqrt(u.^2+v.^2+w.^2),1,'cubic');
x = interp3(x,1); y = interp3(y,1); z = interp3(z,1);
%-- remove randomly 90% of the data
I = randperm(numel(vel0));
velNaN = vel0;
velNaN(I(1:round(numel(I)*.9))) = NaN;
%-- inpaint using INPAINTN
vel = inpaintn(velNaN);
%-- display the results
subplot(221), imagesc(velNaN(:,:,15)), axis equal off
title('Corrupt plane, z = 15')
subplot(222), imagesc(vel(:,:,15)), axis equal off
title('Reconstructed plane, z = 15')
subplot(223)
hsurfaces = slice(x,y,z,vel0,[xmin,100,xmax],ymax,zmin);
set(hsurfaces,'FaceColor','interp','EdgeColor','none')
hcont = contourslice(x,y,z,vel0,[xmin,100,xmax],ymax,zmin);
set(hcont,'EdgeColor',[.7,.7,.7],'LineWidth',.5)
view(3), daspect([2,2,1]), axis tight
title('Actual data compared with...')
subplot(224)
hsurfaces = slice(x,y,z,vel,[xmin,100,xmax],ymax,zmin);
set(hsurfaces,'FaceColor','interp','EdgeColor','none')
hcont = contourslice(x,y,z,vel,[xmin,100,xmax],ymax,zmin);
set(hcont,'EdgeColor',[.7,.7,.7],'LineWidth',.5)
view(3), daspect([2,2,1]), axis tight
title('... reconstructed data')
end
%% DCTN
function y = dctn(y)
%DCTN N-D discrete cosine transform.
% Y = DCTN(X) returns the discrete cosine transform of X. The array Y is
% the same size as X and contains the discrete cosine transform
% coefficients. This transform can be inverted using IDCTN.
%
% Reference
% ---------
% Narasimha M. et al, On the computation of the discrete cosine
% transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936.
%
% Example
% -------
% RGB = imread('autumn.tif');
% I = rgb2gray(RGB);
% J = dctn(I);
% imshow(log(abs(J)),[]), colormap(jet), colorbar
%
% The commands below set values less than magnitude 10 in the DCT matrix
% to zero, then reconstruct the image using the inverse DCT.
%
% J(abs(J)<10) = 0;
% K = idctn(J);
% figure, imshow(I)
% figure, imshow(K,[0 255])
%
% -- Damien Garcia -- 2008/06, revised 2011/11
% -- www.BiomeCardio.com --
y = double(y);
sizy = size(y);
y = squeeze(y);
dimy = ndims(y);
% Some modifications are required if Y is a vector
if isvector(y)
dimy = 1;
if size(y,1)==1, y = y.'; end
end
% Weighting vectors
w = cell(1,dimy);
for dim = 1:dimy
n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim);
w{dim} = exp(1i*(0:n-1)'*pi/2/n);
end
% --- DCT algorithm ---
if ~isreal(y)
y = complex(dctn(real(y)),dctn(imag(y)));
else
for dim = 1:dimy
siz = size(y);
n = siz(1);
y = y([1:2:n 2*floor(n/2):-2:2],:);
y = reshape(y,n,[]);
y = y*sqrt(2*n);
y = ifft(y,[],1);
y = bsxfun(@times,y,w{dim});
y = real(y);
y(1,:) = y(1,:)/sqrt(2);
y = reshape(y,siz);
y = shiftdim(y,1);
end
end
y = reshape(y,sizy);
end
%% IDCTN
function y = idctn(y)
%IDCTN N-D inverse discrete cosine transform.
% X = IDCTN(Y) inverts the N-D DCT transform, returning the original
% array if Y was obtained using Y = DCTN(X).
%
% Reference
% ---------
% Narasimha M. et al, On the computation of the discrete cosine
% transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936.
%
% Example
% -------
% RGB = imread('autumn.tif');
% I = rgb2gray(RGB);
% J = dctn(I);
% imshow(log(abs(J)),[]), colormap(jet), colorbar
%
% The commands below set values less than magnitude 10 in the DCT matrix
% to zero, then reconstruct the image using the inverse DCT.
%
% J(abs(J)<10) = 0;
% K = idctn(J);
% figure, imshow(I)
% figure, imshow(K,[0 255])
%
% See also DCTN, IDSTN, IDCT, IDCT2, IDCT3.
%
% -- Damien Garcia -- 2009/04, revised 2011/11
% -- www.BiomeCardio.com --
y = double(y);
sizy = size(y);
y = squeeze(y);
dimy = ndims(y);
% Some modifications are required if Y is a vector
if isvector(y)
dimy = 1;
if size(y,1)==1
y = y.';
end
end
% Weighing vectors
w = cell(1,dimy);
for dim = 1:dimy
n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim);
w{dim} = exp(1i*(0:n-1)'*pi/2/n);
end
% --- IDCT algorithm ---
if ~isreal(y)
y = complex(idctn(real(y)),idctn(imag(y)));
else
for dim = 1:dimy
siz = size(y);
n = siz(1);
y = reshape(y,n,[]);
y = bsxfun(@times,y,w{dim});
y(1,:) = y(1,:)/sqrt(2);
y = ifft(y,[],1);
y = real(y*sqrt(2*n));
I = (1:n)*0.5+0.5;
I(2:2:end) = n-I(1:2:end-1)+1;
y = y(I,:);
y = reshape(y,siz);
y = shiftdim(y,1);
end
end
y = reshape(y,sizy);
end
|
github | LucaDeSiena/MuRAT-master | vtkwrite.m | .m | MuRAT-master/Utilities_Matlab/VTKWRITE/vtkwrite.m | 11,698 | utf_8 | b2d2311772bb3c962cf4c421b43f3ea2 | function vtkwrite( filename,dataType,varargin )
% VTKWRITE Writes 3D Matlab array into VTK file format.
% vtkwrite(filename,'structured_grid',x,y,z,'vectors',title,u,v,w) writes
% a structured 3D vector data into VTK file, with name specified by the string
% filename. (u,v,w) are the vector components at the points (x,y,z). x,y,z
% should be 3-D matrices like those generated by meshgrid, where
% point(ijk) is specified by x(i,j,k), y(i,j,k) and z(i,j,k).
% The matrices x,y,z,u,v,w must all be the same size and contain
% corrresponding position and vector component. The string title specifies
% the name of the vector field to be saved.
%
% vtkwrite(filename,'structured_grid',x,y,z,'scalars',title,r) writes a 3D
% scalar data into VTK file whose name is specified by the string
% filename. r is the scalar value at the points (x,y,z). The matrices
% x,y,z,r must all be the same size and contain the corresponding position
% and scalar values.
%
% vtkwrite(filename,'structured_grid',x,y,z,'vectors',title,u,v,w,'scalars',
% title2,r) writes a 3D structured grid that contains both vector and scalar values.
% x,y,z,u,v,w,r must all be the same size and contain the corresponding
% positon, vector and scalar values.
%
% vtkwrite(filename, 'structured_points', title, m) saves matrix m (could
% be 1D, 2D or 3D array) into vtk as structured points.
%
% vtkwrite(filename, 'structured_points', title, m, 'spacing', sx, sy, sz)
% allows user to specify spacing. (default: 1, 1, 1). This is the aspect
% ratio of a single voxel.
%
% vtkwrite(filename, 'structured_points', title, m, 'origin', ox, oy, oz)
% allows user to speicify origin of dataset. (default: 0, 0, 0).
%
% vtkwrite(filename,'unstructured_grid',x,y,z,'vectors',title,u,v,w,'scalars',
% title2,r) writes a 3D unstructured grid that contains both vector and scalar values.
% x,y,z,u,v,w,r must all be the same size and contain the corresponding
% positon, vector and scalar values.
%
% vtkwrite(filename, 'polydata', 'lines', x, y, z) exports a 3D line where
% x,y,z are coordinates of the points that make the line. x, y, z are
% vectors containing the coordinates of points of the line, where point(n)
% is specified by x(n), y(n) and z(n).
%
% vtkwrite(filename,'polydata','lines',x,y,z,'Precision',n) allows you to
% specify precision of the exported number up to n digits after decimal
% point. Default precision is 3 digits.
%
% vtkwrite(filename,'polydata','triangle',x,y,z,tri) exports a list of
% triangles where x,y,z are the coordinates of the points and tri is an
% m*3 matrix whose rows denote the points of the individual triangles.
%
% vtkwrite(filename,'polydata','tetrahedron',x,y,z,tetra) exports a list
% of tetrahedrons where x,y,z are the coordinates of the points
% and tetra is an m*4 matrix whose rows denote the points of individual
% tetrahedrons.
%
% vtkwrite('execute','polydata','lines',x,y,z) will save data with default
% filename ''matlab_export.vtk' and automatically loads data into
% ParaView.
%
% Version 2.3
% Copyright, Chaoyuan Yeh, 2016
% Codes are modified from William Thielicke and David Gingras's submission.
if strcmpi(filename,'execute'), filename = 'matlab_export.vtk'; end
fid = fopen(filename, 'w');
% VTK files contain five major parts
% 1. VTK DataFile Version
fprintf(fid, '# vtk DataFile Version 2.0\n');
% 2. Title
fprintf(fid, 'VTK from Matlab\n');
binaryflag = any(strcmpi(varargin, 'BINARY'));
if any(strcmpi(varargin, 'PRECISION'))
precision = num2str(varargin{find(strcmpi(vin, 'PRECISION'))+1});
else
precision = '2';
end
switch upper(dataType)
case 'STRUCTURED_POINTS'
title = varargin{1};
m = varargin{2};
if any(strcmpi(varargin, 'spacing'))
sx = varargin{find(strcmpi(varargin, 'spacing'))+1};
sy = varargin{find(strcmpi(varargin, 'spacing'))+2};
sz = varargin{find(strcmpi(varargin, 'spacing'))+3};
else
sx = 1;
sy = 1;
sz = 1;
end
if any(strcmpi(varargin, 'origin'))
ox = varargin{find(strcmpi(varargin, 'origin'))+1};
oy = varargin{find(strcmpi(varargin, 'origin'))+2};
oz = varargin{find(strcmpi(varargin, 'origin'))+3};
else
ox = 0;
oy = 0;
oz = 0;
end
[nx, ny, nz] = size(m);
setdataformat(fid, binaryflag);
fprintf(fid, 'DATASET STRUCTURED_POINTS\n');
fprintf(fid, 'DIMENSIONS %d %d %d\n', nx, ny, nz);
fprintf(fid, ['SPACING ', num2str(sx), ' ', num2str(sy), ' ',...
num2str(sz), '\n']);
fprintf(fid, ['ORIGIN ', num2str(ox), ' ', num2str(oy), ' ',...
num2str(oz), '\n']);
fprintf(fid, 'POINT_DATA %d\n', nx*ny*nz);
fprintf(fid, ['SCALARS ', title, ' float 1\n']);
fprintf(fid,'LOOKUP_TABLE default\n');
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, m(:)');
else
fwrite(fid, m(:)', 'float', 'b');
end
case {'STRUCTURED_GRID','UNSTRUCTURED_GRID'}
% 3. The format data proper is saved in (ASCII or Binary). Use
% fprintf to write data in the case of ASCII and fwrite for binary.
if numel(varargin)<6, error('Not enough input arguments'); end
setdataformat(fid, binaryflag);
% fprintf(fid, 'BINARY\n');
x = varargin{1};
y = varargin{2};
z = varargin{3};
if sum(size(x)==size(y) & size(y)==size(z))~=length(size(x))
error('Input dimesions do not match')
end
n_elements = numel(x);
% 4. Type of Dataset ( can be STRUCTURED_POINTS, STRUCTURED_GRID,
% UNSTRUCTURED_GRID, POLYDATA, RECTILINEAR_GRID or FIELD )
% This part, dataset structure, begins with a line containing the
% keyword 'DATASET' followed by a keyword describing the type of dataset.
% Then the geomettry part describes geometry and topology of the dataset.
if strcmpi(dataType,'STRUCTURED_GRID')
fprintf(fid, 'DATASET STRUCTURED_GRID\n');
fprintf(fid, 'DIMENSIONS %d %d %d\n', size(x,1), size(x,2), size(x,3));
else
fprintf(fid, 'DATASET UNSTRUCTURED_GRID\n');
end
fprintf(fid, ['POINTS ' num2str(n_elements) ' float\n']);
output = [x(:)'; y(:)'; z(:)'];
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, output);
else
fwrite(fid, output, 'float', 'b');
end
% 5.This final part describe the dataset attributes and begins with the
% keywords 'POINT_DATA' or 'CELL_DATA', followed by an integer number
% specifying the number of points of cells. Other keyword/data combination
% then define the actual dataset attribute values.
fprintf(fid, ['\nPOINT_DATA ' num2str(n_elements)]);
% Parse remaining argument.
vidx = find(strcmpi(varargin,'VECTORS'));
sidx = find(strcmpi(varargin,'SCALARS'));
if vidx~=0
for ii = 1:length(vidx)
title = varargin{vidx(ii)+1};
% Data enteries begin with a keyword specifying data type
% and numeric format.
fprintf(fid, ['\nVECTORS ', title,' float\n']);
output = [varargin{ vidx(ii) + 2 }(:)';...
varargin{ vidx(ii) + 3 }(:)';...
varargin{ vidx(ii) + 4 }(:)'];
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, output);
else
fwrite(fid, output, 'float', 'b');
end
% fwrite(fid, [reshape(varargin{vidx(ii)+2},1,n_elements);...
% reshape(varargin{vidx(ii)+3},1,n_elements);...
% reshape(varargin{vidx(ii)+4},1,n_elements)],'float','b');
end
end
if sidx~=0
for ii = 1:length(sidx)
title = varargin{sidx(ii)+1};
fprintf(fid, ['\nSCALARS ', title,' float\n']);
fprintf(fid, 'LOOKUP_TABLE default\n');
if ~binaryflag
spec = ['%0.', precision, 'f '];
fprintf(fid, spec, varargin{ sidx(ii) + 2});
else
fwrite(fid, varargin{ sidx(ii) + 2}, 'float', 'b');
end
% fwrite(fid, reshape(varargin{sidx(ii)+2},1,n_elements),'float','b');
end
end
case 'POLYDATA'
fprintf(fid, 'ASCII\n');
if numel(varargin)<4, error('Not enough input arguments'); end
x = varargin{2}(:);
y = varargin{3}(:);
z = varargin{4}(:);
if numel(varargin)<4, error('Not enough input arguments'); end
if sum(size(x)==size(y) & size(y)==size(z))~= length(size(x))
error('Input dimesions do not match')
end
n_elements = numel(x);
fprintf(fid, 'DATASET POLYDATA\n');
if mod(n_elements,3)==1
x(n_elements+1:n_elements+2,1)=[0;0];
y(n_elements+1:n_elements+2,1)=[0;0];
z(n_elements+1:n_elements+2,1)=[0;0];
elseif mod(n_elements,3)==2
x(n_elements+1,1)=0;
y(n_elements+1,1)=0;
z(n_elements+1,1)=0;
end
nbpoint = numel(x);
fprintf(fid, ['POINTS ' num2str(nbpoint) ' float\n']);
spec = [repmat(['%0.', precision, 'f '], 1, 9), '\n'];
output = [x(1:3:end-2), y(1:3:end-2), z(1:3:end-2),...
x(2:3:end-1), y(2:3:end-1), z(2:3:end-1),...
x(3:3:end), y(3:3:end), z(3:3:end)]';
fprintf(fid, spec, output);
switch upper(varargin{1})
case 'LINES'
if mod(n_elements,2)==0
nbLine = 2*n_elements-2;
else
nbLine = 2*(n_elements-1);
end
conn1 = zeros(nbLine,1);
conn2 = zeros(nbLine,1);
conn2(1:nbLine/2) = 1:nbLine/2;
conn1(1:nbLine/2) = conn2(1:nbLine/2)-1;
conn1(nbLine/2+1:end) = 1:nbLine/2;
conn2(nbLine/2+1:end) = conn1(nbLine/2+1:end)-1;
fprintf(fid,'\nLINES %d %d\n',nbLine,3*nbLine);
fprintf(fid,'2 %d %d\n',[conn1';conn2']);
case 'TRIANGLE'
ntri = length(varargin{5});
fprintf(fid,'\nPOLYGONS %d %d\n',ntri,4*ntri);
fprintf(fid,'3 %d %d %d\n',(varargin{5}-1)');
case 'TETRAHEDRON'
ntetra = length(varargin{5});
fprintf(fid,'\nPOLYGONS %d %d\n',ntetra,5*ntetra);
fprintf(fid,'4 %d %d %d %d\n',(varargin{5}-1)');
end
end
fclose(fid);
if strcmpi(filename,'matlab_export.vtk')
switch computer
case {'PCWIN','PCWIN64'}
!paraview.exe --data='matlab_export.vtk' &
% Exclamation point character is a shell escape, the rest of the
% input line will be sent to operating system. It can not take
% variables, though. The & at the end of line will return control to
% Matlab even when the outside process is still running.
case {'GLNXA64','MACI64'}
!paraview --data='matlab_export.vtk' &
end
end
end
function setdataformat(fid, binaryflag)
if ~binaryflag
fprintf(fid, 'ASCII\n');
else
fprintf(fid, 'BINARY\n');
end
end
|
github | LucaDeSiena/MuRAT-master | colMapGen.m | .m | MuRAT-master/Utilities_Matlab/COLORMAP/colMapGen.m | 3,113 | utf_8 | a2cb6d462c88f7316457c16e3547033b |
function [colMap] = colMapGen(topCol,botCol,numCol,varargin)
% Creates a colormap using two boundary colors and one middle
% color. Both boundary colors blend into the middle color.
% By default, the middle color is white. This can be changed using
% the 'midCol' name-value pair argument. Input colors must be in RGB
% triplet format (e.g. [0 0 0] for black). The user defines the number
% of colors (segments) to make up the colormap (i.e from the first
% boundary color to the second boundary color).
%%%% Example usage %%%%
% colMap = colMapGen([1 1 0],[0 0 0],20);
% creates a colormap going from yellow to black, with a white
% center. Colormap consists of 20 segments going from yellow to
% black.
% colMap = colMapGen([0 1 1],[0 0 1],100,'midCol',[0 0 0]);
% creates a colormap going from red to blue in 100 segments. The
% middle color is set to black.
% Once a colormap is generated, upload to current figure using:
% colormap(gca,colMap)
% parse inputs - all inputs required except midCol, which is a
% name-value argument
p = inputParser;
addRequired(p,'topCol',@isnumeric); % required function input
addRequired(p,'botCol',@isnumeric); % required function input
addRequired(p,'numCol',@isnumeric); % required function input
addParameter(p,'midCol',[1 1 1],@isnumeric); % varargin input
parse(p,topCol,botCol,numCol,varargin{:}); % parse inputs
topCol = p.Results.topCol; % define function variable from inputs
botCol = p.Results.botCol; % define function variable from inputs
numCol = p.Results.numCol; % define function variable from inputs
midCol = p.Results.midCol; % define function variable from inputs
%%%% creates the upper portion of the colormap
col1_topCol = linspace(topCol(1),midCol(1),round(numCol/2,0)); % 1st RGB triplet of topCol, from topCol(1) to midCol(1)
col2_topCol = linspace(topCol(2),midCol(2),round(numCol/2,0)); % 2nd RGB triplet of topCol, from topCol(2) to midCol(2)
col3_topCol = linspace(topCol(3),midCol(3),round(numCol/2,0)); % 3rd RGB triplet of topCol, from topCol(3) to midCol(3)
RGB1 = [col1_topCol',col2_topCol',col3_topCol']; % matrix of RGB triplets (in rows), going from topCol to midCol
%%%% creates the lower portion of the colormap
col1_botCol = linspace(botCol(1),midCol(1),round(numCol/2,0)); % 1st RGB triplet of botCol, from botCol(1) to midCol(1)
col2_botCol = linspace(botCol(2),midCol(2),round(numCol/2,0)); % 2nd RGB triplet of botCol, from botCol(2) to midCol(2)
col3_botCol = linspace(botCol(3),midCol(3),round(numCol/2,0)); % 3rd RGB triplet of botCol, from botCol(3) to midCol(3)
RGB2 = [col1_botCol',col2_botCol',col3_botCol']; % matrix of RGB triplets (in rows), going from botCol to midCol
%%%% Final colormap
colMap = [RGB2;flipud(RGB1)]; % creates the final colMap by concatenating the bottom colormap with the flipped top colormap
end
|
github | LucaDeSiena/MuRAT-master | fwrite_sac.m | .m | MuRAT-master/Utilities_Matlab/F_SAC/fwrite_sac.m | 14,136 | utf_8 | a0783d7ee600d31d1d6413745197c71f | function sac_mat = fwrite_sac(sac_mat, varargin)
% FWRITE_SAC Write a SAC struct variable into a binary file.
%#########################################
%# #
%# [Function] #
%# Write SAC-formatted files #
%# #
%# #
%# by Whyjay, Jan 2015 #
%#########################################
%
% >> sac_mat = FWRITE_SAC(sac_mat)
% >> sac_mat = FWRITE_SAC(sac_mat, filename)
% >> sac_mat = FWRITE_SAC(sac_mat, filename, machine_fmt)
%
%----Input Variables----------------------------------------------------------
% sac_mat -> SAC data-pack struct, specified in 3 fields.
% sac_mat.t -> 1-D time array, i.e. t
% If omitted, SAC_MAT.HDR.E or SAC_MAT.HDR.DELTA is needed.
% sac_mat.data -> 1-D data array, i.e. f(t)
% If omitted, no any data but only header is written to output.
% sac_mat.hdr -> 1-by-1 struct. the field names and types are the same with
% SAC header version 6. please see Reference for more details.
% If the time information (i.e. HDR.B, HDR.E, HDR.DELTA)
% is omitted, SAC_MAT.T is needed.
% e.g. to access header KSTNM, it's
% >> sac_mat.hdr.kstnm (all the fieldnames are lower case.)
% to access T0 to T9, it's
% >> sac_mat.hdr.t (it's a 1-by-10 array, saving T0 - T9.)
% filename -> File name. 1-D String array.
% machine_fmt -> String that specifies the character encoding scheme
% associated with the file. It can be 'b' or 'ieee-be' for
% big-endian; 'l' or 'ieee-le' for little-endian. If omitted,
% the program uses the local encoding scheme.
%
%----Reference----------------------------------------------------------------
% [1] Header fieldnames reference: http://www.iris.edu/files/sac-manual/
% [2] function FREAD_SAC could help create SAC_MAT struct format from a SAC file.
%
%----Output Variables---------------------------------------------------------
% sac_mat -> Verified SAC data-pack struct. The program may change some
% headers of the original SAC_MAT.HDR if the time information
% is not consistent. The program also auto fills the omitted
% field in SAC_MAT.HDR with its default value.
%
%----Usage--------------------------------------------------------------------
% SAC_MAT = FWRITE_SAC(SAC_MAT) verifies and completes header data in SAC_MAT.HDR
%
% FWRITE_SAC(SAC_MAT, FILENAME) writes SAC_MAT into FILENAME.
%
% FWRITE_SAC(SAC_MAT, FILENAME, MACHINE_FMT) specifies the character encoding scheme.
%
%----Example-----------------------------------------------------------------
%
% [TASK 1] save a time sequence into .sac file
% >> hum.t = linspace(0,1,201);
% >> hum.data = humps(hum.t);
% >> fwrite_sac(hum, 'humps.sac');
%
% [TASK 2] auto-complete all the header information
% >> sacmat.data = sin(0:pi/180:2*pi);
% >> sacmat.hdr.delta = pi/180;
% >> sacmat.hdr.b = 0;
% >> sacmat.hdr.kstnm = 'TEST';
% >> sacmat = fwrite_sac(sacmat);
%
%----Lisensing---------------------------------------------------------------
%
% FWRITE_SAC
% AUTHOR: Whyjay Zheng
% E-MAIL: [email protected]
% CREATED: 2015.01.14
% Copyright (c) 2015, Whyjay Zheng
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
%====Check input: nargin====
if nargin >= 4
error('Too many input arguments.')
elseif nargin == 3
machine_fmt_list = {'b', 'l', 'ieee-be', 'ieee-le'};
if sum(strcmp(varargin{2},machine_fmt_list))
machine_fmt = varargin{2};
else
error('Wrong Machine Format. only ''b'', ''l'', ''ieee-be'', ''ieee-le'' can be accepted.')
end
elseif nargin == 2
machine_fmt = 'n';
end
%====Check input: sac_mat====
if ~isstruct(sac_mat)
error('Input is not a struct variable.')
elseif ~isfield(sac_mat, 'hdr')
sac_mat.hdr = struct('b', 0);
elseif ~isstruct(sac_mat.hdr)
error('Header is not a struct variable.')
elseif length(sac_mat.hdr) == 0
sac_mat.hdr(1).b = 0;
end
%====Verify Header====
hdr_verified = check_hdr(sac_mat.hdr);
hdr_verified = check_data(sac_mat, hdr_verified);
sac_mat.hdr = hdr_verified;
%====Start Writing File, if needed====
if nargin == 2 | nargin == 3
w_action(varargin{1}, sac_mat, machine_fmt);
end
%#####################################################
%## function 'check_hdr' code ##
%#####################################################
function hdr = check_hdr(hdr)
% Check hdr struct availability, and fill the missing headers with -12345.
%
%----Input Variables----------------------------------------------------------
% hdr -> SAC header struct.
%
%----Output Variables---------------------------------------------------------
% hdr_verified -> just like input, but all the essential field are filled
% with undefined value: -12345.
%
%====Settings...====
hdr_list = {'delta', 'depmin', 'depmax', 'scale', 'odelta',...
'b', 'e', 'o', 'a', 't', 'f', 'resp',...
'stla', 'stlo', 'stel', 'stdp', 'evla', 'evlo', 'evel', 'evdp',...
'mag', 'user', 'dist', 'az', 'baz', 'gcarc', 'depmen',...
'cmpaz', 'cmpinc', 'xminimum', 'xmaximum', 'yminimum', 'ymaximum'...
'nzyear', 'nzjday', 'nzhour', 'nzmin', 'nzsec', 'nzmsec',...
'nvhdr', 'norid', 'nevid', 'npts', 'nwfid', 'nxsize', 'nysize',...
'iftype', 'idep', 'iztype', 'iinst', 'istreg', 'ievreg', 'ievtyp',...
'iqual', 'isynth', 'imagtyp', 'imagsrc',...
'leven', 'lpspol', 'lovrok', 'lcalda',...
'kstnm', 'kevnm', 'khole', 'ko', 'ka', 'kt', 'kf',...
'kuser', 'kcmpnm', 'knetwk', 'kdatrd', 'kinst'};
existence = isfield(hdr, hdr_list);
lack_hdr = hdr_list(find(~existence));
%====Start to fill the lacking headers====
for key = lack_hdr
switch key{:}(1)
case 'k' % All the headers which begins with 'k' has a default of '-12345'
if strcmp(key{:},'kt') % except KT and KUSER, since they are 10-by-8 and 3-by-8 text arrays.
hdr.(key{:}) = repmat('-12345 ', 10, 1);
elseif strcmp(key{:},'kuser')
hdr.(key{:}) = repmat('-12345 ', 3, 1);
else
hdr.(key{:}) = '-12345';
end
case 'l' % All the headers which begins with 'l' have a default of 0, except LEVEN
if strcmp(key{:},'leven') % default vaule of LEVEN is 1 (evenly spaced).
hdr.(key{:}) = 1;
elseif strcmp(key{:},'lovrok') % default vaule of LOVROK is 1 (enable overwrite).
hdr.(key{:}) = 1;
else
hdr.(key{:}) = 0;
end
case {'t', 'r', 'u'} % All the headers which begins with 't', 'r' and 'u'
hdr.(key{:}) = -12345 * ones(10,1); % have a default of -12345 * ones(10,1)
otherwise
if strcmp(key{:},'nvhdr') % default vaule of NVHDR is 6 (header version).
hdr.(key{:}) = 6;
elseif strcmp(key{:},'b') % default vaule of B is 0 (begin time).
hdr.(key{:}) = 0;
elseif strcmp(key{:},'iftype') % default vaule of IFTYPE is 1 (time series data).
hdr.(key{:}) = 1;
else
hdr.(key{:}) = -12345; % The other headers have a a default of -12345.
end
end
end
%#####################################################
%## function 'check_data' code ##
%#####################################################
function hdr_verified = check_data(sac_mat, hdr_verified)
% Check data availability, and overwrite some header related to time.
%
%----Input Variables----------------------------------------------------------
% sac_mat -> SAC data struct. must has fieldname 'hdr'.
% hdr_verified -> header struct after function CHECK_HDR.
%
%----Output Variables---------------------------------------------------------
% hdr_verified -> just like input, but some headers possibly have changed.
% headers that may be changed: B, E, DELTA, NPTS.
%
%====If no sac_mat.data ... Only write headers====
if ~isfield(sac_mat, 'data')
hdr_verified.e = hdr_verified.b;
hdr_verified.npts = 0;
hdr_verified.delta = 0;
%====If there's no any time tag ... ERROR====
elseif hdr_verified.e - (-12345) < eps & hdr_verified.delta - (-12345) < eps & ~isfield(sac_mat, 't')
error('Time is not properly specified or not given. Please edit header or time array.')
%====Time tag priority when conflicted: sac_mat.t > sac_mat.hdr.delta > sac_mat.hdr.e====
elseif isfield(sac_mat, 't')
if length(sac_mat.t) ~= length(sac_mat.data)
error('Number of Time and Data points are inconsistent.')
end
hdr_verified.b = sac_mat.t(1);
hdr_verified.e = sac_mat.t(end);
hdr_verified.npts = length(sac_mat.data);
if length(sac_mat.data) <= 1
hdr_verified.delta = 0;
else
hdr_verified.delta = sac_mat.t(2) - sac_mat.t(1);
end
elseif isfield(sac_mat.hdr, 'delta')
hdr_verified.npts = length(sac_mat.data);
if hdr_verified.b - (-12345) > eps
hdr_verified.e = hdr_verified.b + hdr_verified.delta * (length(sac_mat.data) - 1);
elseif hdr_verified.e - (-12345) > eps
hdr_verified.b = hdr_verified.e - hdr_verified.delta * (length(sac_mat.data) - 1);
else
error('Time is not properly specified. (No Begin and End.)')
end
else %if isfield(sac_mat.hdr, 'e')
if hdr_verified.b - (-12345) > eps
error('Time is not properly specified. (No Begin or Delta.)')
end
hdr_verified.npts = length(sac_mat.data);
hdr_verified.delta = (hdr_verified.e - hdr_verified.b) / (length(sac_mat.data) - 1);
end
%#####################################################
%## function 'w_action' code ##
%#####################################################
function w_action(filename, sac_mat, machine_fmt)
% Write SAC struct into file.
%
%----Input Variables----------------------------------------------------------
% filename -> Writing File name. 1-D text array.
% sac_mat -> SAC data struct. must has fieldname 'hdr'.
% machine_fmt -> FOPEN-supported format. e.g. 'b', 'l', 'ieee-be', 'ieee-le'
%
hdr = sac_mat.hdr;
f = fopen(filename, 'w', machine_fmt);
fmt = 'float32';
fwrite(f, hdr.delta, fmt);
fwrite(f, hdr.depmin, fmt);
fwrite(f, hdr.depmax, fmt);
fwrite(f, hdr.scale, fmt);
fwrite(f, hdr.odelta, fmt);
fwrite(f, hdr.b, fmt);
fwrite(f, hdr.e, fmt);
fwrite(f, hdr.o, fmt);
fwrite(f, hdr.a, fmt);
fwrite(f, -12345, fmt);
fwrite(f, hdr.t, fmt);
fwrite(f, hdr.f, fmt);
fwrite(f, hdr.resp, fmt);
fwrite(f, hdr.stla, fmt);
fwrite(f, hdr.stlo, fmt);
fwrite(f, hdr.stel, fmt);
fwrite(f, hdr.stdp, fmt);
fwrite(f, hdr.evla, fmt);
fwrite(f, hdr.evlo, fmt);
fwrite(f, hdr.evel, fmt);
fwrite(f, hdr.evdp, fmt);
fwrite(f, hdr.mag, fmt);
fwrite(f, hdr.user, fmt);
fwrite(f, hdr.dist, fmt);
fwrite(f, hdr.az, fmt);
fwrite(f, hdr.baz, fmt);
fwrite(f, hdr.gcarc, fmt);
fwrite(f, -12345, fmt);
fwrite(f, -12345, fmt);
fwrite(f, hdr.depmen, fmt);
fwrite(f, hdr.cmpaz, fmt);
fwrite(f, hdr.cmpinc, fmt);
fwrite(f, hdr.xminimum, fmt);
fwrite(f, hdr.xmaximum, fmt);
fwrite(f, hdr.yminimum, fmt);
fwrite(f, hdr.ymaximum, fmt);
fwrite(f, -12345 * ones(7,1), fmt);
fmt = 'int32';
fwrite(f, hdr.nzyear, fmt);
fwrite(f, hdr.nzjday, fmt);
fwrite(f, hdr.nzhour, fmt);
fwrite(f, hdr.nzmin, fmt);
fwrite(f, hdr.nzsec, fmt);
fwrite(f, hdr.nzmsec, fmt);
fwrite(f, hdr.nvhdr, fmt);
fwrite(f, hdr.norid, fmt);
fwrite(f, hdr.nevid, fmt);
fwrite(f, hdr.npts, fmt);
fwrite(f, -12345, fmt);
fwrite(f, hdr.nwfid, fmt);
fwrite(f, hdr.nxsize, fmt);
fwrite(f, hdr.nysize, fmt);
fwrite(f, -12345, fmt);
fwrite(f, hdr.iftype, fmt);
fwrite(f, hdr.idep, fmt);
fwrite(f, hdr.iztype, fmt);
fwrite(f, -12345, fmt);
fwrite(f, hdr.iinst, fmt);
fwrite(f, hdr.istreg, fmt);
fwrite(f, hdr.ievreg, fmt);
fwrite(f, hdr.ievtyp, fmt);
fwrite(f, hdr.iqual, fmt);
fwrite(f, hdr.isynth, fmt);
fwrite(f, hdr.imagtyp, fmt);
fwrite(f, hdr.imagsrc, fmt);
fwrite(f, -12345 * ones(8,1), fmt);
fwrite(f, hdr.leven, fmt);
fwrite(f, hdr.lpspol, fmt);
fwrite(f, hdr.lovrok, fmt);
fwrite(f, hdr.lcalda, fmt);
fwrite(f, -12345, fmt);
fmt = 'char';
fwrite(f, sprintf('%-8s', hdr.kstnm), fmt);
fwrite(f, sprintf('%-16s', hdr.kevnm), fmt);
fwrite(f, sprintf('%-8s', hdr.khole), fmt);
fwrite(f, sprintf('%-8s', hdr.ko), fmt);
fwrite(f, sprintf('%-8s', hdr.ka), fmt);
fwrite(f, hdr.kt', fmt);
fwrite(f, sprintf('%-8s', hdr.kf), fmt);
fwrite(f, hdr.kuser', fmt);
fwrite(f, sprintf('%-8s', hdr.kcmpnm), fmt);
fwrite(f, sprintf('%-8s', hdr.knetwk), fmt);
fwrite(f, sprintf('%-8s', hdr.kdatrd), fmt);
fwrite(f, sprintf('%-8s', hdr.kinst), fmt);
if isfield(sac_mat,'data')
fwrite(f, sac_mat.data, 'float32');
end
fclose(f);
|
github | LucaDeSiena/MuRAT-master | fread_sac.m | .m | MuRAT-master/Utilities_Matlab/F_SAC/fread_sac.m | 12,145 | utf_8 | c6aa24aba27e817a7b2e978bb200ae22 | function varargout = fread_sac(varargin)
% FREAD_SAC Read SAC-formatted files and save as struct variables.
%#########################################
%# #
%# [Function] #
%# Read SAC-formatted files #
%# #
%# #
%# by Whyjay, Jan 2015 #
%#########################################
%
% >> FREAD_SAC(filename)
% >> [t, data, hdr] = FREAD_SAC(filename)
% >> sac_mat = FREAD_SAC(filename)
% >> [sac_mat1, sac_mat2, ...] = FREAD_SAC(filename1, filename2, ...)
% >> [...] = FREAD_SAC(..., machine_fmt)
%
%----Input Variables----------------------------------------------------------
% filename -> File name. String array or Cell array. See Usage below.
% machine_fmt -> String that specifies the character encoding scheme
% associated with the file. It can be 'b' or 'ieee-be' for
% big-endian; 'l' or 'ieee-le' for little-endian. If omitted,
% the program uses the local encoding scheme.
%
%----Reference----------------------------------------------------------------
% [1] Header fieldnames reference: http://www.iris.edu/files/sac-manual/
%
%----Output Variables---------------------------------------------------------
% t -> 1-D time records in a SAC file (from header B to header E).
% data -> 1-D data records in a SAC file.
% hdr -> Header structure. its fieldnames are the same with SAC
% header version 6. Please see Reference for more details.
% e.g. to access header KSTNM, it's
% >> hdr.kstnm (all the fieldnames are lower case.)
% to access T0 to T9, it's
% >> hdr.t (it's a 1-by-10 array, saving T0 - T9.)
% ##: header T, RESP, USER are all 1-by-10 arrays.
% header KT, KUSER are 8-by-10 and 3-by-10 arrays,
% each row represents one value (i.e. KT1, KT2,...)
% sac_mat -> SAC data-pack struct. it packs T, DATA, HDR as a single
% varible, and naming SAC_MAT.T, SAC_MAT.DATA, SAC_MAT.HDR.
% e.g. to access SAC data, it's
% >> sac_mat.data
% to access header STLO, it's
% >> sac_mat.hdr.stlo
%
%----Usage--------------------------------------------------------------------
% FREAD_SAC(FILENAME) reads single file, and illustrate it by time-series plot.
%
% [T, DATA, HDR] = FREAD_SAC(FILENAME) reads single file, and saves as T, DATA,
% HDR separately.
%
% SAC_MAT = FREAD_SAC(FILENAME) reads one or multiple files, and saves as SAC_MAT.
% If FILENAME contains N files in 2-D text array or 1-D cell array,
% SAC_MAT would be a 1-by-N cell array with N SAC data-pack struct.
%
% [SAC_MAT1, SAC_MAT2, ...] = FREAD_SAC(FILENAME1, FILENAME2, ...) reads multiple
% files, and saves to different variables.
%
% [...] = FREAD_SAC(..., MACHINE_FMT) specifies the character encoding scheme.
%
%----Example-----------------------------------------------------------------
%
% >> loca = fread_sac('LOCA.sac')
% ---> read 'LOCA.sac' into loca struct.
% >> [loca_e, loca_n, loca_z] = fread_sac('LOCA_E.sac', 'LOCA_N.sac', 'LOCA_Z.sac')
% ---> multiple reading
% >> loca = fread_sac({'LOCA_E.sac', 'LOCA_N.sac', 'LOCA_Z.sac'}, 'l')
% ---> read multile files into loca cell array,
% in little-endian encoding.
% loca{1} => E, loca{2} => N, loca{3} => Z
%
%----Lisensing---------------------------------------------------------------
%
% FREAD_SAC
% AUTHOR: Whyjay Zheng
% E-MAIL: [email protected]
% CREATED: 2015.01.14
% Copyright (c) 2015, Whyjay Zheng
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
%====Set Machine Format (native, little-endian or big-endian)====
machine_fmt_list = {'b', 'l', 'ieee-be', 'ieee-le'};
fmt = 'n';
num_argin = nargin;
if ischar(varargin{end})
if sum(strcmp(varargin{end}(1,:),machine_fmt_list))
fmt = varargin{end};
varargin(end) = [];
num_argin = num_argin -1;
end
end
%====Check Input Type====
if nargin == 0
error('No Inputs.')
else
for every_arg = varargin
if ~or(ischar(every_arg{:}), iscell(every_arg{:}))
error('Input must be text strings or a cell array.')
end
end
end
%====Start Reading File====
%====Type 1: [a, b, c,...] = fread_sac('A', 'B', 'C',...)====
if num_argin ~= 1
if nargout == num_argin
for i=1:length(varargin)
[t, data, hdr] = single_read(varargin{i},fmt);
varargout{i} = struct('hdr',hdr,'t',t,'data',data);
end
else
error('Number of arguments error.')
end
%====Type 2: a = fread_sac('A')====
elseif nargout == 1
if ischar(varargin{1}) & size(varargin{1},1) == 1
[t, data, hdr] = single_read(varargin{1},fmt);
varargout{1} = struct('hdr',hdr,'t',t,'data',data);
%====Type 3: set = fread_sac(['A';'B';...]) or set = fread_sac({'A','B',...})====
else
if iscell(varargin{1}), fileset = varargin{1}; end
if ischar(varargin{1}), fileset = (varargin{1})'; end
varargout{1} = {};
for fname = fileset
if iscell(fname), fname = fname{1}; end
[t, data, hdr] = single_read(reshape(fname,1,[]),fmt);
varargout{1}{end+1} = struct('hdr',hdr,'t',t,'data',data);
end
end
%====Type 4: [t, data, hdr] = fread_sac('A')====
elseif ischar(varargin{1}) & size(varargin{1},1) == 1
if nargout == 3
[varargout{1:3}] = single_read(varargin{1},fmt);
%====Type 5: fread_sac('A') (no output argument)====
elseif nargout == 0
[t, data, hdr] = single_read(varargin{1},fmt);
plot(t, data)
title(varargin{1})
tex = sprintf('%d %d, %d:%d''%d"%d %s-%s',...
hdr.nzyear, hdr.nzjday, hdr.nzhour, hdr.nzmin,...
hdr.nzsec, hdr.nzmsec, hdr.kstnm, hdr.kcmpnm);
legend(tex)
else
error('Number of arguments error.')
end
else
error('Number of arguments error.')
end
%#####################################################
%## function 'single_read' code ##
%#####################################################
function [t, data, hdr] = single_read(filename, machine_fmt)
% Read single SAC file, and Save it into 3 parts.
%
%----Input Variables----------------------------------------------------------
% filename -> Filename you want to read
% machine_fmt -> FOPEN-supported format. e.g. 'b', 'l', 'ieee-be', 'ieee-le'
%
%----Output Variables---------------------------------------------------------
% t -> SAC data time sequence: t 1-D array.
% data -> SAC data time sequence: f(t) 1-D array.
% hdr -> SAC header (Version 6). It's a struct variable.
% field names are the same with header names (in lower case).
%
f=fopen(filename, 'r', machine_fmt);
if f==-1
errtext = sprintf('File "%s" doesn''t exist. Please check input.',filename);
error(errtext);
end
hdr_pt1 = fread(f, 70, 'float32');
hdr_pt2 = fread(f, 40, 'int32');
hdr_pt3 = (fread(f, 192, 'char'))';
hdr = hdr_construct(hdr_pt1, hdr_pt2, hdr_pt3);
%====If SAC header version ~= 6... ====
if hdr.nvhdr ~= 6
fprintf('Your file %s may not contain a SAC version-6 header.\n', filename)
fprintf('Please check your file format and encoding scheme.\n')
continued = input('Do you want to continue reading? y/[n] :', 's');
if ~strcmp(lower(continued), 'y')
fclose(f);
error('Not a SAC version-6 header.')
end
end
data = fread(f, hdr.npts, 'float32');
t = (hdr.b : hdr.delta : (hdr.npts-1)*hdr.delta+hdr.b)';
fclose(f);
%#####################################################
%## function 'hdr_construct' code ##
%#####################################################
function hdr = hdr_construct(hdr_pt1, hdr_pt2, hdr_pt3)
% Construct the SAC header struct.
%
%----Input Variables----------------------------------------------------------
% hdr_ptX -> header information, passed by SINGLE_READ.
%
%----Output Variables---------------------------------------------------------
% ndr -> header struct.
%
% Header fieldnames reference: http://www.iris.edu/files/sac-manual/
% Example: hdr.kstnm for header KSTNM
hdr.delta = hdr_pt1(1);
hdr.depmin = hdr_pt1(2);
hdr.depmax = hdr_pt1(3);
hdr.scale = hdr_pt1(4);
hdr.odelta = hdr_pt1(5);
hdr.b = hdr_pt1(6);
hdr.e = hdr_pt1(7);
hdr.o = hdr_pt1(8);
hdr.a = hdr_pt1(9);
hdr.t = hdr_pt1(11:20); % T0 - T9
hdr.f = hdr_pt1(21);
hdr.resp = hdr_pt1(22:31); % RESP0 - RESP9
hdr.stla = hdr_pt1(32);
hdr.stlo = hdr_pt1(33);
hdr.stel = hdr_pt1(34);
hdr.stdp = hdr_pt1(35);
hdr.evla = hdr_pt1(36);
hdr.evlo = hdr_pt1(37);
hdr.evel = hdr_pt1(38);
hdr.evdp = hdr_pt1(39);
hdr.mag = hdr_pt1(40);
hdr.user = hdr_pt1(41:50); % USER0 - USER9
hdr.dist = hdr_pt1(51);
hdr.az = hdr_pt1(52);
hdr.baz = hdr_pt1(53);
hdr.gcarc = hdr_pt1(54);
hdr.depmen = hdr_pt1(57);
hdr.cmpaz = hdr_pt1(58);
hdr.cmpinc = hdr_pt1(59);
hdr.xminimum = hdr_pt1(60);
hdr.xmaximum = hdr_pt1(61);
hdr.yminimum = hdr_pt1(62);
hdr.ymaximum = hdr_pt1(63);
hdr.nzyear = hdr_pt2(1);
hdr.nzjday = hdr_pt2(2);
hdr.nzhour = hdr_pt2(3);
hdr.nzmin = hdr_pt2(4);
hdr.nzsec = hdr_pt2(5);
hdr.nzmsec = hdr_pt2(6);
hdr.nvhdr = hdr_pt2(7);
hdr.norid = hdr_pt2(8);
hdr.nevid = hdr_pt2(9);
hdr.npts = hdr_pt2(10);
hdr.nwfid = hdr_pt2(12);
hdr.nxsize = hdr_pt2(13);
hdr.nysize = hdr_pt2(14);
hdr.iftype = hdr_pt2(16);
hdr.idep = hdr_pt2(17);
hdr.iztype = hdr_pt2(18);
hdr.iinst = hdr_pt2(20);
hdr.istreg = hdr_pt2(21);
hdr.ievreg = hdr_pt2(22);
hdr.ievtyp = hdr_pt2(23);
hdr.iqual = hdr_pt2(24);
hdr.isynth = hdr_pt2(25);
hdr.imagtyp = hdr_pt2(26);
hdr.imagsrc = hdr_pt2(27);
hdr.leven = hdr_pt2(36);
hdr.lpspol = hdr_pt2(37);
hdr.lovrok = hdr_pt2(38);
hdr.lcalda = hdr_pt2(39);
hdr.kstnm = deblank(char(hdr_pt3(1:8)));
hdr.kevnm = deblank(char(hdr_pt3(9:24)));
hdr.khole = deblank(char(hdr_pt3(25:32)));
hdr.ko = deblank(char(hdr_pt3(33:40)));
hdr.ka = deblank(char(hdr_pt3(41:48)));
hdr.kt = (reshape(char(hdr_pt3(49:128)),8,10))'; % KT0 - KT9
hdr.kf = deblank(char(hdr_pt3(129:136)));
hdr.kuser = (reshape(char(hdr_pt3(137:160)),8,3))'; % KUSER0 - KUSER2
hdr.kcmpnm = deblank(char(hdr_pt3(161:168)));
hdr.knetwk = deblank(char(hdr_pt3(169:176)));
hdr.kdatrd = deblank(char(hdr_pt3(177:184)));
hdr.kinst = deblank(char(hdr_pt3(185:192)));
|
github | LucaDeSiena/MuRAT-master | Murat_test.m | .m | MuRAT-master/Utilities_Matlab/MyUtilities/Murat_test.m | 4,824 | utf_8 | 33a4360f329c71f7e4cf2e0acd3156ef | function [image, SAChdr] = Murat_test(nameWaveform,...
centralFrequencies,smoothingC,figOutput,verboseOutput)
% TEST seismogram envelopes for changes in broadening
% CREATES a figure with seismograms and envelopes for different frequencies
%
% Input Parameters:
% nameWaveform: name of the SAC file
% centralFrequencies: vector of frequencies (Hz),if [] no filter
% smoothingCoefficient: coefficient to smooth envelopes
% figOutput: decide if you want to show figures (set 1)
% verboseOutput: decide if you want to show messages (set 1)
%
% Output:
% image: image with envelope at specified frequency
% SAChdr: header of the SAC file
%
% Imports SAC files
[times,sisma,SAChdr] = fget_sac(nameWaveform);
image = [];
%% Figure
if figOutput == 1
srate_i = 1/SAChdr.times.delta;
sisma = detrend(sisma,1);
lsis = length(sisma);
tu = tukeywin(lsis,0.05);
tsisma = tu.*sisma;
image = figure('Name',['Test Seismograms: '...
nameWaveform],'NumberTitle','off','Position',[20,400,1200,1000]);
lengthFrequencies = length(centralFrequencies);
plotFrequencies = 1:2:2*lengthFrequencies;
if isequal(centralFrequencies,[])
plot(times,sisma,'k-','LineWidth',2);
xlim([SAChdr.times.a - 5 SAChdr.times.a + 20])
SetFDefaults
else
for i = 1:lengthFrequencies
% Filter creation - in loop for each frequency
cf = centralFrequencies(i);
Wn = ([cf-cf/3 cf+cf/3]/srate_i*2);
[z,p,k] = butter(4,Wn,'bandpass');
[sos,g] = zp2sos(z,p,k);
fsisma = filtfilt(sos,g,tsisma);
hsp_i = hilbert(fsisma);
sp_i = smooth(abs(hsp_i),smoothingC/cf*srate_i);
subplot(lengthFrequencies,2,plotFrequencies(i));
plot(times,fsisma,'k-','LineWidth',2);
xlabel('Time (s)')
ylabel('Amplitude')
SetFDefaults
subplot(lengthFrequencies,2,plotFrequencies(i)+1);
plot(times,sp_i,'k-','LineWidth',2);
xlabel('Time (s)')
ylabel('Energy')
SetFDefaults
end
end
end
%%
% Checking all metadata
if verboseOutput == 1
fprintf('<strong> Checking temporal metadata.</strong>\n');
if isequal(SAChdr.times.o,-12345)
disp('Origin (o) is not set.')
else
disp(['Origin (o) at ' num2str(SAChdr.times.o) ' s.'])
end
if isequal(SAChdr.times.a,-12345)
disp('P wave picking (a) is not set.')
else
disp(['P wave picking (a) at ' num2str(SAChdr.times.a) ' s.'])
end
if isequal(SAChdr.times.t0,-12345)
disp('S wave picking (t0) is not set.')
else
disp(['S wave picking (t0) at ' num2str(SAChdr.times.t0) ' s.'])
end
fprintf('<strong> Checking event location metadata.</strong>\n');
if isequal(SAChdr.event.evla,-12345)
disp('Event latitude (evla) is not set.')
else
disp(['Event latitude (evla) at ' num2str(SAChdr.event.evla)...
' degrees.'])
end
if isequal(SAChdr.event.evlo,-12345)
disp('Event longitude (evlo) is not set.')
else
disp(['Event longitude (evlo) at ' num2str(SAChdr.event.evlo)...
' degrees.'])
end
if isequal(SAChdr.event.evdp,-12345)
disp('Event depth (evdp) is not set.')
else
disp(['Event depth (evdp) at ' num2str(SAChdr.event.evdp) ' km.'])
end
fprintf('<strong> Checking station location metadata.</strong>\n');
if isequal(SAChdr.station.stla,-12345)
disp('Station latitude (stla) is not set.')
else
disp(['Station latitude (stla) at ' num2str(SAChdr.station.stla)...
' degrees.'])
end
if isequal(SAChdr.station.stlo,-12345)
disp('Station longitude (stlo) is not set.')
else
disp(['Station longitude (stlo) at ' num2str(SAChdr.station.stlo)...
' degrees.'])
end
if isequal(SAChdr.station.stel,-12345)
disp('Station elevation (stel) is not set.')
else
disp(['Station elevation (stel) at ' num2str(SAChdr.station.stel)...
' m.'])
end
end
function SetFDefaults()
% DEFAULT settings for MuRAt figures
ax = gca;
ax.GridColor = [0 0 0];
ax.GridLineStyle = '--';
ax.GridAlpha = 0.3;
ax.LineWidth = 1.5;
ax.FontSize = 12;
grid on |
github | LucaDeSiena/MuRAT-master | Murat_changeHdr.m | .m | MuRAT-master/Utilities_Matlab/MyUtilities/Murat_changeHdr.m | 1,907 | utf_8 | 6bc33f6d31d6da6139f47c74360de77d | %% CHANGES the header of sac files to include the pickings for MSH
function seism = Murat_changeHdr(newFolder)
% function seism = Murat_changeHdr(newfolder)
% CHANGES header of a file
%
% Input Parameters:
% newFolder: folder where you save the changed file
%
% Output:
% seism: new seismogram
%
[file,path] = uigetfile('*.*');
if isequal(file,0)
error('User selected Cancel!');
else
disp(['User selected ', fullfile(path,file)]);
end
seism = fread_sac(fullfile(path,file));
hs = seism.hdr;
Field =...
["Event Latitude";"Event Longitude";"Event depth (km)";...
"Station Latitude";"Station Longitude"; "Station elevation (m)";...
"Origin time"; "P time"; "S time"];
Value =...
[hs.evla;hs.evlo;hs.evdp;...
hs.stla;hs.stlo;hs.stel;...
hs.o;hs.a;hs.t(1)];
requiredFields = table(Field,Value);
disp(requiredFields);
changeAsk =...
input('What do you want to change?\n Nothing?\n Event (1)?\n Station (2)?\n Time (3)?');
switch changeAsk
case 1
hs.evla = input('Event latitude?');
hs.evlo = input('Event longitude?');
hs.evdp = input('Event depth?');
case 2
hs.stla = input('Station latitude?');
hs.stlo = input('Station longitude?');
hs.stel = input('Station elevation?');
case 3
hs.o = input('Origin time?');
hs.a = input('P time?');
hs.t(1) = input('S time?');
end
seism.hdr = hs;
fwrite_sac(seism,fullfile(newFolder,file)); |
github | LucaDeSiena/MuRAT-master | Murat_testAll.m | .m | MuRAT-master/Utilities_Matlab/MyUtilities/Murat_testAll.m | 3,301 | utf_8 | f45f33ba1ab04e214045c9260845080a | function [muratHeader,flag] = Murat_testAll(folderPath)
% TEST all seismograms in a folder for the input parameters and
% CREATES a file storing the parameters and flagging those missing
%
% Input Parameters:
% folderPath: folder vontaining the SAC data
%
% Output:
% muratHeader: Murat table showing the necessary parameter
%
[Names,~] = createsList(folderPath);
lengthData = length(Names);
Origin = cell(lengthData,1);
P = cell(lengthData,1);
S = cell(lengthData,1);
EvLat = cell(lengthData,1);
EvLon = cell(lengthData,1);
EvDepth = cell(lengthData,1);
StLat = cell(lengthData,1);
StLon = cell(lengthData,1);
StElev = cell(lengthData,1);
for i=1:lengthData
listSac_i = Names{i};
[~,SAChdr] = Murat_test(listSac_i,[],8,0,0);
if isequal(SAChdr.times.o,-12345)
Origin{i} = [];
flag = 1;
else
Origin{i} = SAChdr.times.o;
end
if isequal(SAChdr.times.a,-12345)
P{i} = [];
flag = 1;
else
P{i} = SAChdr.times.a;
end
if isequal(SAChdr.times.t0,-12345)
S{i} = [];
flag = 1;
else
S{i} = SAChdr.times.t0;
end
if isequal(SAChdr.event.evla,-12345)
EvLat{i} = [];
flag = 1;
else
EvLat{i} = SAChdr.event.evla;
end
if isequal(SAChdr.event.evlo,-12345)
EvLon{i} = [];
flag = 1;
else
EvLon{i} = SAChdr.event.evlo;
end
if isequal(SAChdr.event.evdp,-12345)
EvDepth{i} = [];
flag = 1;
else
EvDepth{i} = SAChdr.event.evdp;
end
if isequal(SAChdr.station.stla,-12345)
StLat{i} = [];
flag = 1;
else
StLat{i} = SAChdr.station.stla;
end
if isequal(SAChdr.station.stlo,-12345)
StLon{i} = [];
flag = 1;
else
StLon{i} = SAChdr.station.stlo;
end
if isequal(SAChdr.station.stel,-12345)
StElev{i} = [];
flag = 1;
else
StElev{i} = SAChdr.station.stel;
end
end
muratHeader = table(Names,Origin,P,S,EvLat,EvLon,...
EvDepth,StLat,StLon,StElev);
writetable(muratHeader,'DataHeaders.xls');
end
%%
function [listWithFolder,listNoFolder]...
= createsList(directory)
% CREATES a list of visible files in a folder, outputs both with and
% without folder
list = dir(directory);
list = list(~startsWith({list.name}, '.'));
listWithFolder = fullfile({list.folder},{list.name})';
listNoFolder = {list.name}';
end |
github | LucaDeSiena/MuRAT-master | corner.m | .m | MuRAT-master/Utilities_Matlab/regtu/corner.m | 8,828 | utf_8 | 0c1b046514caab7971fcc127355e042a | function [k_corner,info] = corner(rho,eta,fig)
%CORNER Find corner of discrete L-curve via adaptive pruning algorithm.
%
% [k_corner,info] = corner(rho,eta,fig)
%
% Returns the integer k_corner such that the corner of the log-log
% L-curve is located at ( log(rho(k_corner)) , log(eta(k_corner)) ).
%
% The vectors rho and eta must contain corresponding values of the
% residual norm || A x - b || and the solution's (semi)norm || x ||
% or || L x || for a sequence of regularized solutions, ordered such
% that rho and eta are monotonic and such that the amount of
% regularization decreases as k increases.
%
% The second output argument describes possible warnings.
% Any combination of zeros and ones is possible.
% info = 000 : No warnings - rho and eta describe a discrete
% L-curve with a corner.
% info = 001 : Bad data - some elements of rho and/or eta are
% Inf, NaN, or zero.
% info = 010 : Lack of monotonicity - rho and/or eta are not
% strictly monotonic.
% info = 100 : Lack of convexity - the L-curve described by rho
% and eta is concave and has no corner.
%
% The warnings described above will also result in text warnings on the
% command line. Type 'warning off Corner:warnings' to disable all
% command line warnings from this function.
%
% If a third input argument is present, then a figure will show the discrete
% L-curve in log-log scale and also indicate the found corner.
% Reference: P. C. Hansen, T. K. Jensen and G. Rodriguez, "An adaptive
% pruning algorithm for the discrete L-curve criterion," J. Comp. Appl.
% Math., 198 (2007), 483-492.
% Per Christian Hansen and Toke Koldborg Jensen, DTU Compute, DTU;
% Giuseppe Rodriguez, University of Cagliari, Italy; Sept. 2, 2011.
% Initialization of data
if length(rho)~=length(eta)
error('Vectors rho and eta must have the same length')
end
if length(rho)<3
error('Vectors rho and eta must have at least 3 elements')
end
rho = rho(:); % Make rho and eta column vectors.
eta = eta(:);
if (nargin < 3) | isempty(fig)
fig = 0; % Default is no figure.
elseif fig < 0,
fig = 0;
end
info = 0;
fin = isfinite(rho+eta); % NaN or Inf will cause trouble.
nzr = rho.*eta~=0; % A zero will cause trouble.
kept = find(fin & nzr);
if isempty(kept)
error('Too many Inf/NaN/zeros found in data')
end
if length(kept) < length(rho)
info = info + 1;
warning('Corner:warnings', ...
['Bad data - Inf, NaN or zeros found in data\n' ...
' Continuing with the remaining data'])
end
rho = rho(kept); % rho and eta with bad data removed.
eta = eta(kept);
if any(rho(1:end-1)<rho(2:end)) | any(eta(1:end-1)>eta(2:end))
info = info + 10;
warning('Corner:warnings', 'Lack of monotonicity')
end
% Prepare for adaptive algorithm.
nP = length(rho); % Number of points.
P = log10([rho eta]); % Coordinates of the loglog L-curve.
V = P(2:nP,:)-P(1:nP-1,:); % The vectors defined by these coordinates.
v = sqrt(sum(V.^2,2)); % The length of the vectors.
W = V./repmat(v,1,2); % Normalized vectors.
clist = []; % List of candidates.
p = min(5, nP-1); % Number of vectors in pruned L-curve.
convex = 0; % Are the pruned L-curves convex?
% Sort the vectors according to the length, the longest first.
[Y,I] = sort(v);
I = flipud(I);
% Main loop -- use a series of pruned L-curves. The two functions
% 'Angles' and 'Global_Behavior' are used to locate corners of the
% pruned L-curves. Put all the corner candidates in the clist vector.
while p < (nP-1)*2
elmts = sort(I(1:min(p, nP-1)));
% First corner location algorithm
candidate = Angles( W(elmts,:), elmts);
if candidate>0,
convex = 1;
end
if candidate & ~any(clist==candidate)
clist = [clist;candidate];
end
% Second corner location algorithm
candidate = Global_Behavior(P, W(elmts,:), elmts);
if ~any(clist==candidate)
clist = [clist; candidate];
end
p = p*2;
end
% Issue a warning and return if none of the pruned L-curves are convex.
if convex==0
k_corner = [];
info = info + 100;
warning('Corner:warnings', 'Lack of convexity')
return
end
% Put rightmost L-curve point in clist if not already there; this is
% used below to select the corner among the corner candidates.
if sum(clist==1) == 0
clist = [1;clist];
end
% Sort the corner candidates in increasing order.
clist = sort(clist);
% Select the best corner among the corner candidates in clist.
% The philosophy is: select the corner as the rightmost corner candidate
% in the sorted list for which going to the next corner candidate yields
% a larger increase in solution (semi)norm than decrease in residual norm,
% provided that the L-curve is convex in the given point. If this is never
% the case, then select the leftmost corner candidate in clist.
vz = find(diff(P(clist,2)) ... % Points where the increase in solution
>= abs(diff(P(clist,1)))); % (semi)norm is larger than or equal
% to the decrease in residual norm.
if length(vz)>1
if(vz(1) == 1), vz = vz(2:end); end
elseif length(vz)==1
if(vz(1) == 1), vz = []; end
end
if isempty(vz)
% No large increase in solution (semi)norm is found and the
% leftmost corner candidate in clist is selected.
index = clist(end);
else
% The corner is selected as described above.
vects = [P(clist(2:end),1)-P(clist(1:end-1),1) ...
P(clist(2:end),2)-P(clist(1:end-1),2)];
vects = sparse(diag(1./sqrt(sum(vects.^2,2)))) * vects;
delta = vects(1:end-1,1).*vects(2:end,2) ...
- vects(2:end,1).*vects(1:end-1,2);
vv = find(delta(vz-1)<=0);
if isempty(vv)
index = clist(vz(end));
else
index = clist(vz(vv(1)));
end
end
% Corner according to original vectors without Inf, NaN, and zeros removed.
k_corner = kept(index);
if fig % Show log-log L-curve and indicate the found corner.
figure(fig); clf
diffrho2 = (max(P(:,1))-min(P(:,1)))/2;
diffeta2 = (max(P(:,2))-min(P(:,2)))/2;
loglog(rho, eta, 'k--o'); hold on; axis square;
% Mark the corner.
loglog([min(rho)/100,rho(index)],[eta(index),eta(index)],':r',...
[rho(index),rho(index)],[min(eta)/100,eta(index)],':r')
% Scale axes to same number of decades.
if abs(diffrho2)>abs(diffeta2),
ax(1) = min(P(:,1)); ax(2) = max(P(:,1));
mid = min(P(:,2)) + (max(P(:,2))-min(P(:,2)))/2;
ax(3) = mid-diffrho2; ax(4) = mid+diffrho2;
else
ax(3) = min(P(:,2)); ax(4) = max(P(:,2));
mid = min(P(:,1)) + (max(P(:,1))-min(P(:,1)))/2;
ax(1) = mid-diffeta2; ax(2) = mid+diffeta2;
end
ax = 10.^ax; ax(1) = ax(1)/2; axis(ax);
xlabel('residual norm || A x - b ||_2')
ylabel('solution (semi)norm || L x ||_2');
title(sprintf('Discrete L-curve, corner at %d', k_corner));
end
% =========================================================================
% First corner finding routine -- based on angles
function index = Angles( W, kv)
% Wedge products
delta = W(1:end-1,1).*W(2:end,2) - W(2:end,1).*W(1:end-1,2);
[mm kk] = min(delta);
if mm < 0 % Is it really a corner?
index = kv(kk) + 1;
else % If there is no corner, return 0.
index = 0;
end
% =========================================================================
% Second corner finding routine -- based on global behavior of the L-curve
function index = Global_Behavior(P, vects, elmts)
hwedge = abs(vects(:,2)); % Abs of wedge products between
% normalized vectors and horizontal,
% i.e., angle of vectors with horizontal.
[An, In] = sort(hwedge); % Sort angles in increasing order.
% Locate vectors for describing horizontal and vertical part of L-curve.
count = 1;
ln = length(In);
mn = In(1);
mx = In(ln);
while(mn>=mx)
mx = max([mx In(ln-count)]);
count = count + 1;
mn = min([mn In(count)]);
end
if count > 1
I = 0; J = 0;
for i=1:count
for j=ln:-1:ln-count+1
if(In(i) < In(j))
I = In(i); J = In(j); break
end
end
if I>0, break; end
end
else
I = In(1); J = In(ln);
end
% Find intersection that describes the "origin".
x3 = P(elmts(J)+1,1)+(P(elmts(I),2)-P(elmts(J)+1,2))/(P(elmts(J)+1,2) ...
-P(elmts(J),2))*(P(elmts(J)+1,1)-P(elmts(J),1));
origin = [x3 P(elmts(I),2)];
% Find distances from the original L-curve to the "origin". The corner
% is the point with the smallest Euclidian distance to the "origin".
dists = (origin(1)-P(:,1)).^2+(origin(2)-P(:,2)).^2;
[Y,index] = min(dists); |
github | LucaDeSiena/MuRAT-master | l_curve_tikh_svd.m | .m | MuRAT-master/Utilities_Matlab/regtu/l_curve_tikh_svd.m | 2,242 | utf_8 | e1bdddd1a72a141b0d242e3b03af8edb | % Parameter Estimation and Inverse Problems, 2nd edition, 2011
% by R. Aster, B. Borchers, C. Thurber
%
% return l curve parematers for Tikhonov Regularization
%
% Routine originally inspired by Per Hansen's l-curve
% program (http://www2.imm.dtu.dk/~pch/Regutools/)
%
%
% [rho,eta,reg_param] = l_curve_tikh(U,s,d,npoints,[alpha_min, alpha_max]) )
%
% INPUT
% U - matrix of data space basis vectors from the svd
% s - vector of singular values
% d - the data vector
% npoints - the number of logarithmically spaced regularization parameters
% [alpha_min, alpha_max] if specified, constrain the logrithmically spaced
% regularization parameter range, otherwise an attempt is made to estimate
% them from the range of singular values
%
% OUTPUT
% eta - the solution norm ||m|| or seminorm ||Lm||
% rho - the residual norm ||G m - d||
% reg_param - corresponding regularization parameters
%
function [rho,eta,reg_param] = l_curve_tikh_svd(U,s,d,npoints,varargin)
% Initialization.
[m,n] = size(U);
[p] = length(s);
% compute the projection, and residual error introduced by the projection
d_proj = U'*d;
dr = norm(d)^2 - norm(d_proj)^2;
%data projections
d_proj = d_proj(1:p);
%scale series terms by singular values
d_proj_scale = d_proj./s;
% initialize storage space
eta = zeros(npoints,1);
rho = eta;
reg_param = eta;
s2 = s.^2;
if size(varargin,2)==0
% set the smallest regularization parameter that will be used
smin_ratio = 16*eps;
reg_param(npoints) = max([s(p),s(1)*smin_ratio]);
% ratio so that reg_param(1) will be s(1)
ratio = (s(1)/reg_param(npoints))^(1/(npoints-1));
end
if size(varargin,2)==2
alpharange=cell2mat(varargin);
reg_param(npoints)=alpharange(2);
ratio=(alpharange(1)/alpharange(2))^(1/(npoints-1));
end
% calculate all the regularization parameters
for i=npoints-1:-1:1
reg_param(i) = ratio*reg_param(i+1);
end
% determine the fit for each parameter
for i=1:npoints
%GSVD filter factors
f = s2./(s2 + reg_param(i)^2);
eta(i) = norm(f.*d_proj_scale);
rho(i) = norm((1-f).*d_proj);
end
% if we couldn't match the data exactly add the projection induced misfit
if (m > n && dr > 0)
rho = sqrt(rho.^2 + dr);
end
|
github | ostwaldd/Variational-Bayes-GLM-master | beh_model_experiment.m | .m | Variational-Bayes-GLM-master/beh_model_experiment.m | 50,096 | utf_8 | b884acb91730dbe9897bb719a7ee8fc5 | function beh_model_experiment(sj_id, run_id)
% This function presents the gridworld search paradigm.
%
% Inputs
% sj_id : participant ID, string
% run_id : run ID, scalar
%
% Outputs
% None, saves results file to disc
%
% Copyright (C) Lilla Horvath, Dirk Ostwald
% -------------------------------------------------------------------------
% -------------------------------------------------------------------------
% ---------------------------- Initialization -----------------------------
% -------------------------------------------------------------------------
clc
close all
% reset the state of the random nubmer generator based on computer clock
rng('shuffle');
% New comment
% -------------------------------------------------------------------------
% ------------------------ Paradigm Parameters ----------------------------
% -------------------------------------------------------------------------
% experimental parameters
dim = 5 ; % grid dimension
n_tgt = 2 ; % number of targets
stim_dir = [pwd '\Stimuli'] ; % stimulus directory
res_dir = [pwd '\Results\' sj_id] ; % participant specific result directory
min_p = 50 ; %
b_max = 3 ; % maximal number of blocks per task
p_lim = [ 0.1 0.2 0.4 0.2 0.1] ; % +- two steps with probabilities given by p
poss_lim = [-2 -1 0 1 2] ; % steps with probabilities given by p
% short vs long stimuli presentation dependent parameters of the experiment
% between subject condition
bsc = 0 ; % between subject condition, 0 corresponds to the long and 1 to the short condition
if bsc == 0
% experimental parameter
n_task = 4 ; % number of tasks per run
% timing parameters
l_s = 3 ; % lower endpoint for the short duration (state and obs pres)
u_s = 5 ; % upper endpoint for the short duration (state and obs pres)
l_l = 6 ; % lower endpoint for the long duration (fixation point)
u_l = 8 ; % upper endpoint for the long duration (fixation point)
elseif bsc == 1
n_task = 8 ; % number of tasks per run
% timing parameters
l_s = 1.5 ; % lower endpoint for the short duration (state and obs pres)
u_s = 2.5 ; % upper endpoint for the short duration (state and obs pres)
l_l = 3 ; % lower endpoint for the long duration (fixation point)
u_l = 4 ; % upper endpoint for the long duration (fixation point)
end
% cue display coordinates (up, down, left, right)
cue_coords = [[0 177];[0 -177]; [-177 0];[177 0]];
% cogent display configuration parameters
cog_ws = 1 ; % window size
cog_rs = 3 ; % display resolution (mapped with laptop screen)
cog_bc = [0 0 0] ; % background color
cog_fc = [1 1 1] ; % foreground color
cog_fn = 'Helvetia' ; % fontname
cog_fs = 45 ; % fontsize
cog_bu = 11 ; % number of offscreen-buffers
cog_bd = 0 ; % bits per pixel
% cogent keyboard configuration parameters
cog_ql = 100 ; % quelength
cog_kr = 5 ; % keyboard resolution
cog_km = 'nonexclusive' ; % keyboard mode
% scanner or behavioural testing flag
isscan = 1 ; % 0: behavioural lab, 1: MR lab
% response keys differentiation
if isscan
% button box "left" keys
% ---------------------------------------------------------------------
% blue , yellow, green , red
% e = 5, w = 23 , n = 14, d = 4
% use cursor keys
k_left = 5;
k_up = 23;
k_down = 14;
k_right = 4;
else
% use cursor keys
k_left = 97;
k_up = 95;
k_down = 100;
k_right = 98;
end
% -------------------------------------------------------------------------
% -------------------------- Stimulus Loading -----------------------------
% -------------------------------------------------------------------------
% grid background stimulus filenames
grid_fname = { 'upper_corner_left_s.jpg' , ...
'upper_corner_right_s.jpg' , ...
'lower_corner_left_s.jpg' , ...
'lower_corner_right_s.jpg' , ...
'side_upper_s.jpg' , ...
'side_left_s.jpg' , ...
'side_right_s.jpg' , ...
'side_lower_s.jpg' , ...
'middle_s.jpg' };
% cue stimulus filenames
cue_fname = { 'dark_hor_s.jpg' ,...
'light_hor_s.jpg' ,...
'dark_ver_s.jpg' ,...
'light_ver_s.jpg' };
% decision prompt filenames
arrow_fname = { 'up_s.jpg' ,...
'down_s.jpg' ,...
'left_s.jpg' ,...
'right_s.jpg' };
% load grid stimuli into workspace and normalize to cogent image format
grid_pict = cell(1,numel(grid_fname));
for i = 1:numel(grid_fname)
grid_pict{i} = double(imread(fullfile(stim_dir,grid_fname{i})))./255;
end
% load cue stimuli into workspace and normalize to cogent image format
cue_pict = cell(1,numel(cue_fname));
for i = 1:numel(cue_fname)
cue_pict{i} = double(imread(fullfile(stim_dir,cue_fname{i})))./255;
end
% load arrow stimuli into workspace and normalize to cogent image format
arrow_pict = cell(1,numel(cue_fname));
for i = 1:numel(cue_fname)
arrow_pict{i} = double(imread(fullfile(stim_dir,arrow_fname{i})))./255;
end
% load target stimulus into workspace and normalize to cogent image format
target = double(imread(fullfile(stim_dir,'treasure2_s.jpg')))./255;
% -------------------------------------------------------------------------
% ----------------------- Paradigm Presentation ---------------------------
% -------------------------------------------------------------------------
% initialize cogent
config_display(cog_ws, cog_rs, cog_bc, cog_fc, cog_fn, cog_fs, cog_bu, cog_bd);
config_keyboard(cog_ql, cog_kr, cog_km);
start_cogent;
% display starting screen
clearpict(1);
preparestring('Ready',1)
drawpict(1);
% differentiate presentation start conditions
% -------------------------------------------------------------------------
if isscan
% wait for and read scanner trigger
outportb(890,32)
startState = inportb(888);
oldValue = startState;
triggerNum = 0;
while triggerNum < 4
val = inportb(888);
if val ~= oldValue
triggerNum = triggerNum + 1;
triggertime(triggerNum) = time;
end
oldValue = val;
end
else
wait(2000);
end
% -------------------------------------------------------------------------
% ------------------------ Initial Fixation Block -------------------------
% -------------------------------------------------------------------------
% clear buffer 2 to default background color
clearpict(2);
% write fixation cross into buffer 2
preparestring('+',2);
% present buffer 2, t_expstart is the time of the experiment start, i.e.
% the scanner trigger synchronized zero time point.
t_expstart = drawpict(2);
% sample fixation duration and wait
dur_fp_i = unifrnd(l_l,u_l)*1000;
wait(dur_fp_i);
% -------------------------------------------------------------------------
% --------------------------- Cycle Over Tasks ----------------------------
% -------------------------------------------------------------------------
% initialize global block counter over tasks
blockcount = 1;
% cycle over tasks
for task = 1:n_task
% sample target position from independent uniform discrete distribution
% ---------------------------------------------------------------------
% initialize target coordinate array
tgt = ones(n_tgt,2);
while tgt(1,:) == 1 || tgt(2,:) == 1
for j = 1 : n_tgt
tgt(j,:) = unidrnd(5,1,2);
end
while isequal(tgt(1,:),tgt(2,:))
for i = n_tgt
tgt(i,:) = unidrnd(5,1,2);
end
end
end
% Observation probability definition
% ---------------------------------------------------------------------
% initialize distance and probability arrays
l1_map_t = NaN(dim, dim, n_tgt);
p_map_t = NaN(dim,dim,n_tgt);
max_l1 = NaN(1,n_tgt);
lin_acc_g = NaN(1,n_tgt);
% cycle over targets
for t = 1:n_tgt
% cycle over matrix rows
for i = 1:dim
% cyle over matrix columns
for j = 1:dim
% evaluate l1 distance to the target for each grid cell and each target
l1_map_t(i,j,t) = pdist([i,j;tgt(t,1),tgt(t,2)], 'cityblock'); % parametrize 1 and 2 later!
end
end
% maximum l1 distance for each target
max_l1(t) = max(max(l1_map_t(:,:,t)));
% linear increase in cue accuracy
lin_acc_g(t) = min_p/(max_l1(t) - 1);
% cue accuracy probability (right direction)
p_map_t(:,:,t) = (100-((l1_map_t(:,:,t) - 1)*lin_acc_g(t)))/100;
end
% join probability maps
p_12 = NaN(dim,dim);
for i = 1:dim
for j = 1:dim
p_12(i,j) = join_p(p_map_t(i,j,1),p_map_t(i,j,2));
end
end
% Optimal number of steps for the current problem
% ---------------------------------------------------------------------
% evaluate the optimal path according to Dijkstra's algorithm
% CAVE: OPTIMAL FORAY USES TGT IN TRANSPOSED FORM - HARMONIZE!!!
optglobalpath = optimal_foray(dim,tgt');
% evaluate the number optimally visited nodes, including the start node
n_opt = size(optglobalpath,2);
% evaluate the number of optimal performed steps
s_opt = n_opt - 1;
% ---------------------------------------------------------------------
% ------------------------ Cycle over Task Blocks ---------------------
% ---------------------------------------------------------------------
for block = 1:b_max
% reset agent position to row 1, column 1 of grid matrix
pos = [1 1];
step_lim = zeros(1,1); % initialize step_lim array
while step_lim < 1 % sample from poss_lim until the step_limit (poss_lim + s_opt) is at least 1
% evaluate the step number limit
step_lim = s_opt + poss_lim(find(logical(mnrnd(1,p_lim))));
end
% initialize block log for current block
blocklog = NaN(step_lim+1,34);
% initialize target found flag
% -----------------------------------------------------------------
% [0 0] : no target found
% [1 0] : target at tgt_coord(1,:) found
% [0 1] : target at tgt_coord(2,:) found
% [1 1] : target at tgt_coord(1,:) and tgt_coord(2,:) found
% -----------------------------------------------------------------
found_t = zeros(1,n_tgt);
f_within_tl = zeros(1,1);
% -----------------------------------------------------------------
% ------------------ Cycle over Block Trials ----------------------
% -----------------------------------------------------------------
for trial = 1:step_lim
% record agent position prior to move
pos_trial = pos;
% Grid Cell State Preparation
% -------------------------------------------------------------
% clear buffer 3 to default background color
clearpict(3);
% write the respective background grid image into buffer 3
preparepict(grid_pict{get_pictidx(pos, dim)},3);
% additionally write the target to buffer 3, if appropriate,
for t = 1:n_tgt
% show image only if the target has not been found previously
if isequal(pos,tgt(t,:)) && found_t(t) == 0
% write targt into buffer 3
preparepict(target,3,-70,-70);
% set target found flag to 1
found_t(t) = 1;
end
end
% additionally write fixation cross into buffer 3
preparestring('+',3);
% additionally write string of current grid index into buffer 3
preparestring(['(',num2str(pos(1)),' , ', num2str(pos(2)),')'],3,70,-70);
% additionally evaluate and write string of number of trials
% left and targets found into buffer 3
preparestring([num2str(step_lim - trial + 1), ' (' num2str(sum(found_t)),')'],3,-190,190);
% Grid Cell State Presentation
% -------------------------------------------------------------
% present the grid cell state
t_s = drawpict(3);
% evaluate state presentation time wrt experiment start
t_s = t_s - t_expstart;
% evaluate state presentation duration
dur_s = unifrnd(l_s,u_s)*1000;
% present for dur_s
wait(dur_s)
% Observation Preparation
% -------------------------------------------------------------
% clear buffer 4 to default background color
clearpict(4);
% differentiate l1 distance and probability maps
if ~ismember(1, found_t) % no target found so far
p_map = p_12;
l1_map = l1_map_t;
elseif found_t(1) == 1 && found_t(2) == 0 % target 1 found, target 2 not found
p_map = p_map_t(:,:,2);
l1_map = l1_map_t(:,:,2);
elseif found_t(1) == 0 && found_t(2) == 1 % target 1 not found, target 2 found
p_map = p_map_t(:,:,1);
l1_map = l1_map_t(:,:,1);
elseif found_t(1) == 1 && found_t(2) == 1 % both targets found
% end the loop over trials, go to final state presentation
f_within_tl = 1;
% block-log array for trial loop - variables of trial where
% goal reached before steps limit reached
% (state presentation only)
% ---------------------------------------------------------
blocklog(trial,1:2) = tgt(1,:) ; % (1:2) target 1 position
blocklog(trial,3:4) = tgt(2,:) ; % (3:4) target 2 position
blocklog(trial,5:6) = found_t ; % (5:6) targets found flag
blocklog(trial,7:8) = pos_trial ; % (7:8) current trial matrix row position
blocklog(trial,9) = block ; % (9) block number (= attempt on this task)
blocklog(trial,10) = f_within_tl ; % (10) both targets found within trial loop flag
blocklog(trial,11) = t_s ; % (11) onset time of trial start/state presentation
break
end
% get cue picture information
[cueidx,d_cue,s_cue,o_cue] = get_cue(pos, l1_map, p_map);
% write cue pictures into buffer 4 (up, down, left, right)
for c = 1:length(cueidx)
% if cueidx is zero, do write image into array
if ~(cueidx(c) == 0)
preparepict(cue_pict{cueidx(c)},4, cue_coords(c,1),cue_coords(c,2));
end
end
% additionally write fixation cross into buffer 4
preparestring('+',4);
% additionally evaluate and write string of number of trials and targets found into buffer 4
preparestring([num2str(step_lim - trial + 1), ' (' num2str(sum(found_t)),')'],4,-190,190);
% Observation Presentation
% -------------------------------------------------------------
% present the observation
t_o = drawpict(4);
% evaluate observation presentation time wrt experiment start
t_o = t_o - t_expstart;
% evaluate observation presentation duration
dur_o = unifrnd(l_s,u_s)*1000;
% present for dur_o
wait(dur_o);
% Decision Prompt Preparation
% -------------------------------------------------------------
% clear buffer 5 to default background color
clearpict(5);
% WRITE GET_ARROWIDX SUBFUNCTION FOR CONSITENCY
if pos(1) ~= 1 % not uppermost row
preparepict(arrow_pict{1},5,0,90); % arrow up
end
if pos(1) ~= dim % not lowermost row
preparepict(arrow_pict{2},5,0,-90); % arrow down
end
if pos(2) ~= 1 % not leftmost column
preparepict(arrow_pict{3},5,-90,0); % arrow left
end
if pos(2) ~= dim % not rightmost column
preparepict(arrow_pict{4},5,90,0); % arrow right
end
% additionally write fixation cross into buffer 5
preparestring('+',5);
% additionally evaluate and write string of number of trials and targets found into buffer 5
preparestring([num2str(step_lim - trial + 1), ' (' num2str(sum(found_t)),')'],5,-190,190);
% Decision Prompt Presentation
% -------------------------------------------------------------
% present decision prompt
t_c = drawpict(5);
% evaluate decision prompt presentation time
t_c = t_c - t_expstart;
% evaluate maximal decision prompt presentation time
dur_r = unifrnd(l_s,u_s)*1000;
% Read participant responses
% -------------------------------------------------------------
% clears all prior keyboard events
clearkeys;
% read all key events since the last readkeyes
readkeys;
% evaluate keyboard responses
[key_d,t_d] = waitkeydown(dur_r, [k_up,k_left,k_right,k_down]);
% record keyboard response time
t_d = t_d - t_expstart;
% case that the participants responds faster than dur_r
if t_d - t_c < dur_r
% Post-Decision Fixation Preparation
% ---------------------------------------------------------
% clear buffer 6 to default background color
clearpict(6);
% additionally evaluate and write string of number of trials and targets found into buffer 6
preparestring([num2str(step_lim - trial), ' (' num2str(sum(found_t)),')'],6,-190,190);
% write fixation cross to buffer 6
preparestring('+',6);
% present fixation
t_pd_f = drawpict(6);
% present fixation for the remaining time of the response interval
wait(dur_r - (t_d - t_c));
end
% Decision Consequence - Agent movement
% -------------------------------------------------------------
% evaluate decision, if there is one
if ~isempty(key_d)
% evaluate new position based on key press
if key_d == k_up
pos(1) = pos(1) - 1;
elseif key_d == k_down
pos(1) = pos(1) + 1;
elseif key_d == k_left
pos(2) = pos(2) - 1;
elseif key_d == k_right
pos(2) = pos(2) + 1;
end
% make inappropriate steps impossible
for i = 1:length(pos)
if pos(i) < 1
pos(i) = 1 ;
elseif pos(i) > dim
pos(i) = dim;
end
end
% if there is no response the agent remains at its location
else
key_d = NaN;
t_d = NaN;
end
% fill in block-log array
% -------------------------------------------------------------
blocklog(trial,1:2) = tgt(1,:) ; % (1:2) target 1 position
blocklog(trial,3:4) = tgt(2,:) ; % (3:4) target 2 position
blocklog(trial,5:6) = found_t ; % (5:6) targets found flag
blocklog(trial,7:8) = pos_trial ; % (7:8) current trial matrix row position
blocklog(trial,9) = block ; % (9) block number (= attempt on this task)
blocklog(trial,10) = f_within_tl ; % (10) both targets found within trial loop flag
blocklog(trial,11) = t_s ; % (11) onset time of trial start/state presentation
blocklog(trial,12) = t_o ; % (12) onset time of observation presentation
blocklog(trial,13) = t_c ; % (13) onset time of decision cue (arrows) presentation
blocklog(trial,14) = t_d ; % (14) onset time of participant's button press
blocklog(trial,15) = key_d ; % (15) participant/agent decision (NaN = no key pres)
blocklog(trial,16) = t_d - t_c ; % (16) reaction time (button press onset - decision cue onset, NaN: no key press - no reaction time)
blocklog(trial,17:20) = d_cue ; % (17:20) display cue flags
blocklog(trial,21:24) = s_cue ; % (21:24) sample cue flags
blocklog(trial,25:28) = o_cue ; % (25:28) cue sampling outcomes
blocklog(trial,29:32) = cueidx ; % (29:32) cue sampling outcomes
end % trial loop
% -----------------------------------------------------------------
% ------------- Final State Presentation Preparation --------------
% -----------------------------------------------------------------
% clear buffer 7 to default background color
clearpict(7);
% Evaluate target presence
% -----------------------------------------------------------------
if f_within_tl == 0
% write the respective background grid image into buffer 7
preparepict(grid_pict{get_pictidx(pos, dim)},7);
% additionally write the target to buffer 7, if appropriate,
for t = 1:n_tgt
% show image only if the target has not been found previously
if isequal(pos,tgt(t,:)) && found_t(t) == 0
% write targt into buffer 3
preparepict(target,7,-70,-70);
% set target found flag to 1
found_t(t) = 1;
end
end
% additionally write fixation cross to buffer 7
preparestring('+',7);
% additionally write string of current grid index into buffer 7
preparestring(['(',num2str(pos(1)),' , ', num2str(pos(2)),')'],7,70,-70);
% additionally evaluate and write string of number of trials and targets found into buffer 7
preparestring([num2str(step_lim - trial), ' (' num2str(sum(found_t)),')'],7,-190,190);
% Final State Presentation Preparation
% -----------------------------------------------------------------
% present the final state
t_fin_s = drawpict(7);
% evaluate final state presentation time
t_fin_s = t_fin_s - t_expstart;
% evaluate duration of the final state presentation
dur_fin_s = unifrnd(l_s,u_s)*1000;
% present for dur_fin_s
wait(dur_fin_s);
% fill in block-log array for final state
% ---------------------------------------------------------
blocklog(trial+1,1:2) = tgt(1,:) ; % (1:2) target 1 position
blocklog(trial+1,3:4) = tgt(2,:) ; % (3:4) target 2 position
blocklog(trial+1,5:6) = found_t ; % (5:6) targets found flag
blocklog(trial+1,7:8) = pos ; % (7:8) current trial matrix row position
blocklog(trial+1,9) = block ; % (9) block number (= attempt on this task)
blocklog(trial+1,10) = f_within_tl ; % (10) both targets found within trial loop flag (if 0: endstate pres)
blocklog(trial+1,11) = t_fin_s ; % (11) onset time of trial start/state presentation
end
% End of block - case distinction and information presentation
%------------------------------------------------------------------
% Reset Information Preparation
% -----------------------------------------------------------------
clearpict(8);
if sum(found_t) == 2
preparestring('Both targets found',8);
info_block = 1;
else
preparestring('Step Limit Reached',8);
if block < b_max
preparestring('Resetting Position',8, 0,-40);
info_block = 2;
else
preparestring('Attempt Limit Reached',8,0,-40);
info_block = 3;
end
end
t_info = drawpict(8);
% evaluate information presentation time wrt experiment start
t_info = t_info - t_expstart;
% evaluateinformation presentation duration
dur_info = unifrnd(l_s,u_s)*1000;
% present for dur_info
wait(dur_info);
clearpict(9);
t_fix_b = NaN;
dur_fix_b = NaN;
if info_block == 2 && rem(blockcount,4) == 0
preparestring('+',9)
t_fix_b = drawpict(9);
t_fix_b = t_fix_b - t_expstart;
dur_fix_b = unifrnd(l_l,u_l)*1000;
wait(dur_fix_b);
end
% fill in block-log array for block information
% -----------------------------------------------------------------
blocklog(trial+1,12) = info_block ; % (12) type of info at the end of the block
blocklog(trial+1,13) = t_info ; % (13) onset time of information presentation (last state only!)
blocklog(trial+1,14) = step_lim ; % (14) block specific step limit
blocklog(trial+1,15) = s_opt ; % (15) optimal number of steps for task
blocklog(trial+1,16) = t_fix_b ; % (16) onset time of fixation presentation after 4th block
% allocate variable values to runlog array
runlog{blockcount} = blocklog;
% increase blockcounter
blockcount = blockcount + 1;
if block < b_max && sum(found_t) == 2
break
end
end
% End of task - case distinction and information presentation
%------------------------------------------------------------------
% Reset Information Preparation
% -----------------------------------------------------------------
clearpict(10);
if task < n_task
preparestring('Creating New Task', 10);
info_task = 1;
else
preparestring('Task Limit Reached',10);
preparestring('Ending Program',10,0,-40);
info_task = 2;
end
t_info_tl = drawpict(10);
% evaluate information presentation time wrt experiment start
t_info_tl = t_info_tl - t_expstart;
% evaluateinformation presentation duration
dur_info_tl = unifrnd(l_s,u_s)*1000;
% present for dur_info
wait(dur_info_tl);
clearpict(11);
if rem((blockcount-1),4) == 0
preparestring('+',11)
t_fix_b = drawpict(11);
t_fix_b = t_fix_b - t_expstart;
dur_fix_b = unifrnd(l_l,u_l)*1000;
wait(dur_fix_b);
end
% fill in block-log array for end of task
% --------------------------------------------------------------------
blocklog(trial+1,17) = info_task ; % (17) type of info after a task
blocklog(trial+1,18) = t_info_tl ; % (18) onset time of information presentation - end of task
blocklog(trial+1,19) = dur_info_tl ; % (19) duration of info presentation - end of task
blocklog(trial+1,20) = t_fix_b ; % (20) onset time of fixation presentation after 4th block
blocklog(trial+1,21) = dur_fix_b ; % (21) duration of fixation presentation
% % allocate variable values to runlog array
runlog{blockcount-1} = blocklog;
% task specific l1 map
l1_maps_t{task} = l1_map_t;
% task specific p map
p_maps_t{task} = p_map_t;
% task specific joint p map
p_12_maps{task} = p_12;
% task specific optimal steps
s_opt_all{task} = s_opt;
end % task loop
% save
% ---------------------------------------------------------
% save to disc
save(fullfile(res_dir, [sj_id '_Run_' num2str(run_id), '.mat']), 'runlog', 'l1_maps_t', 'p_maps_t', 'p_12_maps', 's_opt_all', 'bsc')
% end cogent
stop_cogent;
end
function [pictidx] = get_pictidx(pos_coord, dim)
% This function returns the indices of pictures in the grid_pict array
% based on the current coordinates of the agent
%
% Inputs
% pos_coord : 2 x 1 array of agent row and column coordinatee
% dim : grid world dimension
%
% Outpus
% pictidx : scalar index for grid_pict array
%
% Copyright (C) Dirk Ostwald
% -------------------------------------------------------------------------
% determine the index
% -------------------------------------------------------------------------
% upper left corner
if pos_coord(1) == 1 && pos_coord(2) == 1
pictidx = 1;
% upper right corner
elseif pos_coord(1) == 1 && pos_coord(2) == dim
pictidx = 2;
% lower left corner
elseif pos_coord(1) == dim && pos_coord(2) == 1
pictidx = 3;
% lower right corner
elseif pos_coord(1) == dim && pos_coord(2) == dim
pictidx = 4;
% uppermost row
elseif pos_coord(1) == 1 && (pos_coord(2) > 1 && pos_coord(2) < dim)
pictidx = 5;
% leftmost row
elseif (pos_coord(1) > 1 && pos_coord(1) < dim) && pos_coord(2) == 1
pictidx = 6;
% rightmost row
elseif (pos_coord(1) > 1 && pos_coord(1) < dim) && pos_coord(2) == dim
pictidx = 7 ;
% lowermost row
elseif pos_coord(1) == dim && (pos_coord(2) > 1 && pos_coord(2) < dim)
pictidx = 8;
% interior of the grid
else
pictidx = 9;
end % grid cell image selection
end
function [cueidx,d_cue,s_cue,o_cue] = get_cue(pos, l1_map, p_map)
% This function specifies four variables, each with two possible values (
% filenames of images), where the current value of the variable depends on
% the function of Manhattan-distance (l1 norm), and the outcome of
% sampling from a Bernoulli distribution
%
% Input
% pos : 1 x 2 array if agent gridworld matrix coordinate
% l1_map : dim x dim x n_tgt array of l1 distances to target
% p_map : dim x dim array of probabilities (joint probability
% or probability map of target1/target2
%
% Output
% cueidx : 4 x 1 (up, down, left, right) array of cue image array
% indices with the semantic
% (0) = no bar
% (1) = dark vertical
% (2) = light vertical
% (3) = dark horizontal
% (4) = light horizontal
% d_cue : 4 x 1 (up, down, left, right) array of display cue flags
% s_cue : 4 x 1 (up, down, left, right) array of sample cue flags
% o_cue : 4 x 1 (up, down, left, right) array of cue sample outcomes
%
% Copyright (C) Lilla Horvath, Dirk Ostwald
% -------------------------------------------------------------------------
%
% Initialization
% -------------------------------------------------------------------------
% recover problem cardinalities
n_act = 4 ; % largest possible action set
n_dim = size(l1_map,1) ; % assuming a square grid world
% evaluate possible future locations("act"ion "o"ut"c"omes)
act_oc = repmat(pos,n_act,1) ;
act_oc(1,1) = act_oc(1,1) - 1 ; % step up
act_oc(2,1) = act_oc(2,1) + 1 ; % step down
act_oc(3,2) = act_oc(3,2) - 1 ; % step left
act_oc(4,2) = act_oc(4,2) + 1 ; % step right
% cue display, sample, and sample outcome flag initialization
% order of flags => up,down,left,right cues
d_cue = NaN(n_act,1) ; % display cue ? (0/1)
s_cue = NaN(n_act,1) ; % sample cue ? (0/1)
o_cue = NaN(n_act,1) ; % sample outcome ? (0/1/NaN = not sampled)
% Evaluation of display, cue, and outcome flags
% -------------------------------------------------------------------------
% cycle over possible action outcomes
for a = 1:n_act
% if action outcome takes the agent of grid, do not display cue and do not sample
if any(act_oc(a,:) < 1) || any(act_oc(a,:) > n_dim)
d_cue(a) = 0;
s_cue(a) = 0;
% if action outcome does not take agent of the grid
else
% display cue
d_cue(a) = 1;
% set sampling flag to zero as default
s_cue(a) = 0;
% if, in addition action outcome decreases l1 distance to any
% target, set sampling flag to 1
for t = 1:size(l1_map,3)
% action outcome decreases distance to target t
if l1_map(act_oc(a,1),act_oc(a,2),t) < l1_map(pos(1),pos(2),t)
% sample cue
s_cue(a) = 1;
end
end
end
end
% sample the relevant cues from a Bernoulli distribution with parameter
% determined from the probability map
for a = 1:n_act
% determine whether to sample or not
if s_cue(a)
% sample cue outcome based on Binomial distribution with n = 1 and
% p as function of probability map and agent position
o_cue(a) = binornd(1,p_map(pos(1), pos(2)));
end
end
% determine cue array index
% -------------------------------------------------------------------------
% cue_array order: (1) dark_hor,(2) light_hor,(3) dark_ver,(4) light_ver
% initialize cueidx to no cue depiction
cueidx = zeros(n_act,1);
% cycle over action set
for a = 1:n_act
% update cueidx, if a cue is to be displayed
if d_cue(a)
% up/down action outcomes -> horizontal bars
if a < 3
% a cue is to be displayed, but it was not sampled -> dark bar
if s_cue(a) == 0
cueidx(a) = 1;
% a cue is to be displyed and it was sampled
else
% determine dark or light horizontal bar
switch o_cue(a)
% 0 was sampled
case 0
% dark horizontal bar is displayed
cueidx(a) = 1;
% 1 was sampled
case 1
% light horizontal bar is displayed
cueidx(a) = 2;
end % switch
end % if
% left/right action outcomes -> vertical bars
else
% a cue is to be displayed, but it was not sampled -> dark bar
if s_cue(a) == 0
cueidx(a) = 3;
% a cue is to be displyed and it was sampled
else
% determine dark or light vertical bar
switch o_cue(a)
% 0 was sampled
case 0
% dark vertical bar is displayed
cueidx(a) = 3;
% 1 was sampled
case 1
% light vertical bar is displayed
cueidx(a) = 4;
end % switch
end% if
end % if
end % if
end % for
end % function
function p_12 = join_p(p_1,p_2)
% This function evaluates weights w_1, w_2 for two Bernoulli distribution
% parameters p_1, p_2 in [0.5,1] such that the weighted sum of p_1 and p_2
% using w_1, w_2, i.e.
%
% p_12 = w_1*p_2 + w_2*p_2
%
% falls into the interval [.5,1].
%
% Inputs
% p_1,p_2 : Bernoulli distribution parameters in [0.5,1]
%
% Outputs
% w_1,w_2 : Bernoulli distribution parameter weights in [0,1]
%
% Copyright (C) Dirk Ostwald
% -------------------------------------------------------------------------
if p_1 >= p_2
p_12 = p_2 + (p_1 - p_2)*p_1;
else
p_12 = p_1 + (p_2 - p_1)*p_2;
end
end
function [optglpathmidxs] = optimal_foray(n,tgt_coord)
% This function is a training script that uses Dijkstra's algorithm to
% determine the optimal foray path to recover size(tgt,2) items in a n x n
% grid-world starting in the upper left corner. The implemenation of
% Dijkstra's algorithm capitalizes on graph notation.
%
% Inputs
% n : scalar indicating the gridworld dimension
% tgt_coords : 2 x number of target array of target coordinates
%
% Output
% optglpathmidxs : 2 x n array of the optimal path in matrix
% coordinates, n corresponds to the number of
% visited nodes
%
% Copyright (C) Dirk Ostwald
% -------------------------------------------------------------------------
clc
close all
% convert matrix target coordinates into graph nodes
% -------------------------------------------------------------------------
% CAVE: Matlab's linear indices increase row-wise, not column-wise,,
% while the optimal foray graph nodes do so vice versa. Hence the
% transposition of the input target coordinates
tgt = NaN(1,size(tgt_coord,2));
for i = 1:size(tgt_coord,2)
tgt(i) = sub2ind([n,n],tgt_coord(2,i),tgt_coord(1,i));
end
% tgt will be constructively destroyed below, thus save in additionally
tgt_mark = tgt;
% graph nodes: a grid world
% -------------------------------------------------------------------------
% specify matrix coordinates = graph nodes
M = NaN(n^2,2);
m_idx = 1;
for i = 1:n
for j = 1:n
M(m_idx,1) = i;
M(m_idx,2) = j;
m_idx = m_idx + 1;
end
end
% graph edges: a grid world adjacency matrix
% -------------------------------------------------------------------------
% initialize as completely unconnected graph
A = zeros(size(M,1));
% specify square grid-world edges row wise
for i = 1:(n^2-1)
% right-most column graph nodes
if mod(i,n) == 0
A(i,i+n) = 1;
% last-row column graph nodes
elseif i >= (n^2 - n)
A(i,i+1) = 1;
% standard case
else
A(i,i+1) = 1;
A(i,i+n) = 1;
end
end
% specify symmetric connections
A = A + A';
% cost matrix for steps between nodes i and j
% -------------------------------------------------------------------------
C = A;
% Determine optimal path
% -------------------------------------------------------------------------
% initialize start node to upper left corner
start_node = 1;
% initialize the optimal global path covering all targets
optglobalpath = 1;
% iteratively determine the optimal global path
while ~isempty(tgt)
% evaluate optimal paths from start_node to remaining target nodes
pathcost = NaN(1,length(tgt));
optpath = cell(1,length(tgt));
for i = 1:length(tgt)
% determine costs and paths using Dijkstra's algorithm
[localcost,localpath] = dijkstras_algorithm(A,C,start_node,tgt(i));
pathcost(i) = localcost;
optpath{i} = localpath;
end
% determine the cheapest path
[minpathcost, minidx] = min(pathcost);
% concatenate the global path, remove starting node
optglobalpath = [optglobalpath optpath{minidx}(2:end)];
% redefine the starting point for the next search
start_node = tgt(minidx);
% remove the target from the target list
tgt(minidx) = [];
end
% reconvert the optimal global path to matrix indices
% -------------------------------------------------------------------------
optglpathmidxs = NaN(2,length(optglobalpath));
for i = 1:length(optglobalpath)
[col,row] = ind2sub([n,n],optglobalpath(i));
optglpathmidxs(1,i) = row;
optglpathmidxs(2,i) = col;
end
% convert graph space into matrix coordinates into Cartesian coordinates
% -------------------------------------------------------------------------
% convert the matrix graph node coordinates to Cartesian coordinates
K = NaN(n^2,2);
for m = 1:size(K,1)
K(m,:) = mat2cart(M(m,:),n);
end
% initialize connection array in matrix index space
src_node_mat = NaN(sum(sum(A)),2);
tgt_node_mat = NaN(sum(sum(A)),2);
src_node_crt = NaN(sum(sum(A)),2);
tgt_node_crt = NaN(sum(sum(A)),2);
% cycle over adjacency matrix rows and colummn
minidx = 1;
for i = 1:size(A,1)
for j = 1:size(A,2)
% there exists a connection between M coordinates n and m
if A(i,j) == 1
src_node_mat(minidx,:) = M(i,:);
tgt_node_mat(minidx,:) = M(j,:);
minidx = minidx + 1;
end
end
end
% convert to list of Cartesian coordinates
for i = 1:size(src_node_mat,1)
src_node_crt(i,:) = mat2cart(src_node_mat(i,:),n);
tgt_node_crt(i,:) = mat2cart(tgt_node_mat(i,:),n);
end
% convert the path defined as edge nodes into matrix coordinates
% -------------------------------------------------------------------------
% initialize path coordinated arrays in matrix and Cartesian space
path_src_node_mat = NaN(length(optglobalpath)-1,2);
path_tgt_node_mat = NaN(length(optglobalpath)-1,2);
path_src_node_crt = NaN(length(optglobalpath)-1,2);
path_tgt_node_crt = NaN(length(optglobalpath)-1,2);
minidx = 1;
for i = 2:length(optglobalpath)
% determine source and target nodes in matrix coordinates
path_src_node_mat(minidx,:) = M(optglobalpath(i-1),:);
path_tgt_node_mat(minidx,:) = M(optglobalpath(i) ,:);
minidx = minidx + 1;
end
% convert matrix coordinate path into list of Cartesian coordinate path
for i = 1:size(path_src_node_mat,1)
path_src_node_crt(i,:) = mat2cart(path_src_node_mat(i,:),n);
path_tgt_node_crt(i,:) = mat2cart(path_tgt_node_mat(i,:),n);
end
% visualize the problem and its solution
% -------------------------------------------------------------------------
% visualize the grid world
do_plot = 0;
if do_plot
h = figure;
set(h, 'Color', [1 1 1])
hold on
plot(K(:,1), K(:,2), 'ko', 'MarkerFaceColor', 'k')
for i = 1:size(src_node_mat,1)
plot([src_node_crt(i,1) tgt_node_crt(i,1)],[src_node_crt(i,2) tgt_node_crt(i,2)])
end
% visualize the target nodes
for i = 1:length(tgt_mark)
plot(K(tgt_mark(i),1), K(tgt_mark(i),2), 'go', 'MarkerFaceColor', 'g')
end
% visualize the optimal path
for i = 1:size(path_src_node_crt,1)
plot([path_src_node_crt(i,1) path_tgt_node_crt(i,1)],[path_src_node_crt(i,2) path_tgt_node_crt(i,2)], 'r', 'LineWidth', 3)
end
xlim([min(K(:,1))-1, max(K(:,1))+1])
ylim([min(K(:,2))-1, max(K(:,2))+1])
axis square
axis off
end
end
function [xy] = mat2cart(ij,n)
% This function transforms matrix coordinates(i,j)to Cartesian coordinates
% (x,y) to allow for straightforward plotting of matrix space properties.
% It implements the mapping
%
% f:N_n^2 -> R^2, (i,j) |-> f(i,j) := (x,y) := (j - (n+1)/2,-i +(n+1)/2 )
%
% where (i,j) refer to matrix row and column indices and (x,y) to Cartesian
% coordinates for a given square matrix size of size n x n. The Cartesian
% coordinates are zero centered at the center of the matrix
%
% Inputs
%
% ij : (2 x 1) array of matrix row index i and column index j
% n : matrix size
%
% Outputs
% xy : (2 x 1) array of Cartesian x-ordinate x and y-ordinate y
%
% Copyright (C) Dirk Ostwald
% -------------------------------------------------------------------------
% implement the transform
% -------------------------------------------------------------------------
xy(1) = ij(2) - ((n + 1)/2);
xy(2) = -ij(1) + ((n + 1)/2);
end
function [costs, paths] = dijkstras_algorithm(A,C,s,f)
% This function implements Dijkstra's algorithm, a dynamic programming
% routine, to evaluate the optimal (lowest cost) path from a specified
% start node to a specified target node on a graph specified by the
% adjacency matrix A with an associated cost matrix for each edge given by
% C. It is based on Joseph Kirk's Matlab implementation of Dijkstra's
% algorithm as available from http://www.mathworks.com/matlabcentral/
% fileexchange/20025-advanced-dijkstras-minimum-path-algorithm
%
% Inputs
%
% A : (n^2 x n^2) adjaency matrix specifying the edges of a graph
% comprising n nodes
% C : (n^2 x n^2) cost matrix specifying the cost associated with
% taking a specific edge
% s : scalar start node
% t : scalar target node
%
% Outputs
%
% costs:
% paths:
%
% Copyright (C) Dirk Ostwald
% -------------------------------------------------------------------------
% recover adjacency matrix size
[n, nc] = size(A);
% recover cost matrix size
[m, mc] = size(C);
% convert adjacency matrix to edge list
[I,J] = find(A);
E = [I J];
cost = C;
L = length(s);
M = length(f);
costs = zeros(L,M);
paths = num2cell(NaN(L,M));
% Find the Minimum Costs and Paths using Dijkstra's Algorithm
for k = 1:L
% Initializations
TBL = sparse(1,n);
min_cost = Inf(1,n);
settled = zeros(1,n);
path = num2cell(nan(1,n));
I = s(k);
min_cost(I) = 0;
TBL(I) = 0;
settled(I) = 1;
path(I) = {I};
while any(~settled(f))
% Update the Table
TAB = TBL;
TBL(I) = 0;
nids = find(E(:,1) == I);
% Calculate the Costs to the Neighbor Points and Record Paths
for kk = 1:length(nids)
J = E(nids(kk),2);
if ~settled(J)
c = cost(I,J);
empty = ~TAB(J);
if empty || (TAB(J) > (TAB(I) + c))
TBL(J) = TAB(I) + c;
path{J} = [path{I} J];
else
TBL(J) = TAB(J);
end
end
end
K = find(TBL);
% Find the Minimum Value in the Table
N = find(TBL(K) == min(TBL(K)));
if isempty(N)
break
else
% Settle the Minimum Value
I = K(N(1));
min_cost(I) = TBL(I);
settled(I) = 1;
end
end
% store Costs and Paths
costs(k,:) = min_cost(f);
paths(k,:) = path(f);
end
if L == 1 && M == 1
paths = paths{1};
end
end
|
github | yu-jiang/Squirrelbot-master | armUI.m | .m | Squirrelbot-master/armUI.m | 6,568 | utf_8 | 11e2a6de0ea54f142ddd1ee62755bc1e | classdef armUI < handle
properties
fig
axis
lines
ac %arduno controller
% Sliders
sliderMotor1
sliderMotor2
sliderMotor3
sliderMotor4
simulationOnly = false;
positionData
buttonConnect
buttonReplay
buttonAddPoint
buttonClear
%
end
methods
function this = armUI()
this.fig = figure('Name', 'Micro Robotic Arm Visualizer', ...
'Position',[400 200 800 400]);
this.ac = arduinoController;
this.positionData = mraSimulator(this.ac.angle1, this.ac.angle2, this.ac.angle3);
this.sliderMotor1 = uicontrol(this.fig, 'style', 'slider', ...
'Max', pi, 'Min', 0, ...
'Value', this.positionData.theta1, ...
'Position', [420 300 360 30], ...
'callback', {@slider1callback, this});
this.sliderMotor2 = uicontrol(this.fig, 'style', 'slider', ...
'Max', pi, 'Min', 0, ...
'Value', this.positionData.theta2, ...
'Position', [420 250 360 30], ...
'callback', {@slider2callback, this});
this.sliderMotor3 = uicontrol(this.fig, 'style', 'slider', ...
'Max', pi, 'Min', 0, ...
'Value', this.positionData.theta3, ...
'Position', [420 200 360 30], ...
'callback', {@slider3callback, this});
this.sliderMotor4 = uicontrol(this.fig, 'style', 'slider', ...
'Max', pi, 'Min', 0, ...
'Value', 0.5*pi, ...
'Position', [420 150 360 30], ...
'callback', {@slider4callback, this});
this.buttonConnect = uicontrol(this.fig, 'style', 'pushButton', ...
'Position', [420 20 90 50], ...,
'String', 'Connect', ...
'callback', {@connectButtonCallback, this});
this.buttonConnect = uicontrol(this.fig, 'style', 'pushButton', ...
'Position', [510 20 90 50], ...,
'String', 'Replay', ...
'callback', {@replayButtonCallback, this});
% this.buttonAddPoint = uicontrol(this.fig, 'style', 'pushButton', ...
% 'Position', [600 20 90 50], ...,
% 'String', 'Log Position', ...
% 'callback', {@addPointButtonCallback, this});
this.buttonClear = uicontrol(this.fig, 'style', 'pushButton', ...
'Position', [690 20 90 50], ...,
'String', 'Clear', ...
'callback', {@clearButtonCallback, this});
[this.lines.l, this.lines.lbase, this.lines.ltrj] = initializeAxes(this);
end
function updateVirtualArm(this)
% Draw auxillary dashed line
set(this.lines.lbase, 'XData', [this.positionData.xyz0(1), this.positionData.xyza(1)]);
set(this.lines.lbase, 'YData', [this.positionData.xyz0(2), this.positionData.xyza(2)]);
set(this.lines.lbase, 'ZData', [this.positionData.xyz0(3), this.positionData.xyza(3)]);
% Draw the arm
set(this.lines.l, 'XData',[this.positionData.xyz0(1) this.positionData.xyz1(1) this.positionData.xyz2(1) this.positionData.xyz3(1)]);
set(this.lines.l, 'YData',[this.positionData.xyz0(2) this.positionData.xyz1(2) this.positionData.xyz2(2) this.positionData.xyz3(2)]);
set(this.lines.l, 'ZData',[this.positionData.xyz0(3) this.positionData.xyz1(3) this.positionData.xyz2(3) this.positionData.xyz3(3)]);
% Draw trajectory
if ~isempty(this.ac.SavedTrj)
set(this.lines.ltrj, 'XData', this.ac.EndPointData(:,1), ...
'YData', this.ac.EndPointData(:,2), ...
'ZData', this.ac.EndPointData(:,3));
end
drawnow;
end
end
methods (Access = protected)
function update(this)
updateVirtualArm(this);
update(this.ac);
end
function updateSliders(this, val)
this.sliderMotor1.Value = val(1);
this.sliderMotor2.Value = val(2);
this.sliderMotor3.Value = val(3);
this.sliderMotor3.Value = val(4);
end
end
%
%
% events
% positionChange
% end
end
% Local functions
function slider1callback(handle,~,this)
this.positionData.theta1 = handle.Value;
this.ac.angle1 = handle.Value;
update(this);
end
function slider2callback(handle,~,this)
this.positionData.theta2 = handle.Value;
this.ac.angle2 = handle.Value;
update(this);
end
function slider3callback(handle,~,this)
this.positionData.theta3 = handle.Value;
this.ac.angle3 = handle.Value;
update(this);
end
function slider4callback(handle,~,this)
this.ac.angle4 = handle.Value;
%this.ac.angle5 = pi - handle.Value;
update(this);
end
function connectButtonCallback(handle, ~, this)
if this.ac.isconnected
disConnectArduino(this.ac);
this.ac.isconnected = false;
else
this.ac.isconnected = connectArduino(this.ac);
end
if this.ac.isconnected
handle.String = 'Disconnect';
end
end
function clearButtonCallback(handle, ~, this)
this.ac.clearSavedTrj;
set(this.lines.ltrj, 'XData', NaN, ...
'YData', NaN, ...
'ZData', NaN);
update(this);
end
function replayButtonCallback(handle, ~, this)
this.ac.autolog = false;
for ct = 1:size(this.ac.SavedTrj, 1);
if any(isnan(this.ac.SavedTrj(ct,:)))
continue
end
this.positionData.copyAngle(this.ac.SavedTrj(ct,:))
this.ac.copyAngle(this.positionData);
update(this);
updateSliders(this, this.ac.SavedTrj(ct,:));
disp(this.ac.SavedTrj(ct,:));
pause(0.01);
end
this.ac.autolog = true;
end
function addPointButtonCallback(handle, ~, this)
this.ac.addTrjPoint([this.ac.angle1 this.ac.angle2 this.ac.angle3 this.ac.angle4]);
update(this);
end
function [l, lbase, ltrj] = initializeAxes(this)
this.fig;
this.axis = gca;
this.axis.Position = [0.1 0.1 0.4 0.8];
axis equal
axis(this.axis, [-5 5 -5 5 0 6]/2);
grid on;
% Draw auxillary dashed line
lbase = line([this.positionData.xyz0(1), this.positionData.xyza(1)], ...
[this.positionData.xyz0(2), this.positionData.xyza(2)], ...
[this.positionData.xyz0(3), this.positionData.xyza(3)], ...
'LineWidth', 2, ...
'LineStyle', '-.',...
'Color', [1 0 0]);
% Draw the arm
l = line([this.positionData.xyz0(1) this.positionData.xyz1(1) this.positionData.xyz2(1) this.positionData.xyz3(1)], ...
[this.positionData.xyz0(2) this.positionData.xyz1(2) this.positionData.xyz2(2) this.positionData.xyz3(2)], ...
[this.positionData.xyz0(3) this.positionData.xyz1(3) this.positionData.xyz2(3) this.positionData.xyz3(3)], ...
'LineWidth', 2);
% Initialize the trajectory
if ~isempty(this.ac.SavedTrj)
this.lines.ltrj = line(this.ac.EndPointData(:,1), ...
this.ac.EndPointData(:,2), ...
this.ac.EndPointData(:,3), ...
'Marker', 'o', 'Color', [0 1 0]);
else
ltrj = line(NaN, NaN, 'Marker', 'o', 'Color', [0 1 0]);
end
end |
github | anduresu/NonLinearOptimizationHW-master | step.m | .m | NonLinearOptimizationHW-master/step.m | 853 | utf_8 | da0005ef212fbebf552e873e78184bf0 | function tk = step( f , x0 )
tg = 0 ;
td = 0 ;
t = 1/2 ;
tk = 0 ;
while tk ~= t
[a,b,c] = golstein_rule( f, x0, t) ;
if a == 1
tk = t ;
end
if b == 1
td = t ;
end
if c == 1
tg = t ;
end
if b == 1 || c == 1
if td == 0
t = 10*tg ;
else
t = (tg + td)/2 ;
end
end
end
end
function [ val , grad0 ] = h( f, x0, t )
d = -eval(subs(jacobian(f),argnames(f),x0)) ;
x_delta = x0 + t*d ;
val = eval(subs(f,argnames(f),x_delta)) - eval(subs(f,argnames(f),x0)) ;
grad0 = eval(subs(gradient(f),argnames(f),x0))*d ;
end
function [ a , b , c ] = golstein_rule( f, x0, t )
a = 0 ;
b = 0 ;
c = 0 ;
m2 = 0.618033989 ;
m1 = 1 - m2 ;
[h_valt, grad_h0] = h(f, x0, t) ;
if ( h_valt > m1*grad_h0*t )
b = 1 ;
end
if ( h_valt < m2*grad_h0*t )
c = 1 ;
end
if b == 0 && c == 0
a = 1 ;
end
end
|
github | cszn/DnCNN-master | Cal_PSNRSSIM.m | .m | DnCNN-master/utilities/Cal_PSNRSSIM.m | 6,569 | utf_8 | c726759a14c4754004b2fbbec4ebbf36 | function [psnr_cur, ssim_cur] = Cal_PSNRSSIM(A,B,row,col)
[n,m,ch]=size(B);
A = A(row+1:n-row,col+1:m-col,:);
B = B(row+1:n-row,col+1:m-col,:);
A=double(A); % Ground-truth
B=double(B); %
e=A(:)-B(:);
mse=mean(e.^2);
psnr_cur=10*log10(255^2/mse);
if ch==1
[ssim_cur, ~] = ssim_index(A, B);
else
ssim_cur = (ssim_index(A(:,:,1), B(:,:,1)) + ssim_index(A(:,:,2), B(:,:,2)) + ssim_index(A(:,:,3), B(:,:,3)))/3;
end
function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L)
%========================================================================
%SSIM Index, Version 1.0
%Copyright(c) 2003 Zhou Wang
%All Rights Reserved.
%
%The author is with Howard Hughes Medical Institute, and Laboratory
%for Computational Vision at Center for Neural Science and Courant
%Institute of Mathematical Sciences, New York University.
%
%----------------------------------------------------------------------
%Permission to use, copy, or modify this software and its documentation
%for educational and research purposes only and without fee is hereby
%granted, provided that this copyright notice and the original authors'
%names appear on all copies and supporting documentation. This program
%shall not be used, rewritten, or adapted as the basis of a commercial
%software or hardware product without first obtaining permission of the
%authors. The authors make no representations about the suitability of
%this software for any purpose. It is provided "as is" without express
%or implied warranty.
%----------------------------------------------------------------------
%
%This is an implementation of the algorithm for calculating the
%Structural SIMilarity (SSIM) index between two images. Please refer
%to the following paper:
%
%Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image
%quality assessment: From error measurement to structural similarity"
%IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004.
%
%Kindly report any suggestions or corrections to [email protected]
%
%----------------------------------------------------------------------
%
%Input : (1) img1: the first image being compared
% (2) img2: the second image being compared
% (3) K: constants in the SSIM index formula (see the above
% reference). defualt value: K = [0.01 0.03]
% (4) window: local window for statistics (see the above
% reference). default widnow is Gaussian given by
% window = fspecial('gaussian', 11, 1.5);
% (5) L: dynamic range of the images. default: L = 255
%
%Output: (1) mssim: the mean SSIM index value between 2 images.
% If one of the images being compared is regarded as
% perfect quality, then mssim can be considered as the
% quality measure of the other image.
% If img1 = img2, then mssim = 1.
% (2) ssim_map: the SSIM index map of the test image. The map
% has a smaller size than the input images. The actual size:
% size(img1) - size(window) + 1.
%
%Default Usage:
% Given 2 test images img1 and img2, whose dynamic range is 0-255
%
% [mssim ssim_map] = ssim_index(img1, img2);
%
%Advanced Usage:
% User defined parameters. For example
%
% K = [0.05 0.05];
% window = ones(8);
% L = 100;
% [mssim ssim_map] = ssim_index(img1, img2, K, window, L);
%
%See the results:
%
% mssim %Gives the mssim value
% imshow(max(0, ssim_map).^4) %Shows the SSIM index map
%
%========================================================================
if (nargin < 2 || nargin > 5)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5); %
K(1) = 0.01; % default settings
K(2) = 0.03; %
L = 255; %
end
if (nargin == 3)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5);
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 5)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
C1 = (K(1)*L)^2;
C2 = (K(2)*L)^2;
window = window/sum(sum(window));
img1 = double(img1);
img2 = double(img2);
mu1 = filter2(window, img1, 'valid');
mu2 = filter2(window, img2, 'valid');
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;
if (C1 > 0 & C2 > 0)
ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
else
numerator1 = 2*mu1_mu2 + C1;
numerator2 = 2*sigma12 + C2;
denominator1 = mu1_sq + mu2_sq + C1;
denominator2 = sigma1_sq + sigma2_sq + C2;
ssim_map = ones(size(mu1));
index = (denominator1.*denominator2 > 0);
ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));
index = (denominator1 ~= 0) & (denominator2 == 0);
ssim_map(index) = numerator1(index)./denominator1(index);
end
mssim = mean2(ssim_map);
return
|
github | cszn/DnCNN-master | DnCNN_Init.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_DagNN_v1.1/DnCNN_Init.m | 5,836 | utf_8 | 094a3b14e2884158ae9137ec571ea0f8 | function net = DnCNN_Init()
% by Kai Zhang (1/2018)
% [email protected]
% https://github.com/cszn
% Create DAGNN object
net = dagnn.DagNN();
% conv + relu
blockNum = 1;
inVar = 'input';
channel= 1; % grayscale image
dims = [3,3,channel,64];
pad = [1,1];
stride = [1,1];
lr = [1,1];
[net, inVar, blockNum] = addConv(net, blockNum, inVar, dims, pad, stride, lr);
[net, inVar, blockNum] = addReLU(net, blockNum, inVar);
for i = 1:15
% conv + bn + relu
dims = [3,3,64,64];
pad = [1,1];
stride = [1,1];
lr = [1,0];
[net, inVar, blockNum] = addConv(net, blockNum, inVar, dims, pad, stride, lr);
n_ch = dims(4);
[net, inVar, blockNum] = addBnorm(net, blockNum, inVar, n_ch);
[net, inVar, blockNum] = addReLU(net, blockNum, inVar);
end
% conv
dims = [3,3,64,channel];
pad = [1,1];
stride = [1,1];
lr = [1,0]; % or [1,1], it does not influence the results
[net, inVar, blockNum] = addConv(net, blockNum, inVar, dims, pad, stride, lr);
% sum
inVar = {inVar,'input'};
[net, inVar, blockNum] = addSum(net, blockNum, inVar);
outputName = 'prediction';
net.renameVar(inVar,outputName)
% loss
net.addLayer('loss', dagnn.Loss('loss','L2'), {'prediction','label'}, {'objective'},{});
net.vars(net.getVarIndex('prediction')).precious = 1;
end
% Add a Concat layer
function [net, inVar, blockNum] = addConcat(net, blockNum, inVar)
outVar = sprintf('concat%d', blockNum);
layerCur = sprintf('concat%d', blockNum);
block = dagnn.Concat('dim',3);
net.addLayer(layerCur, block, inVar, {outVar},{});
inVar = outVar;
blockNum = blockNum + 1;
end
% Add a loss layer
function [net, inVar, blockNum] = addLoss(net, blockNum, inVar)
outVar = 'objective';
layerCur = sprintf('loss%d', blockNum);
block = dagnn.Loss('loss','L2');
net.addLayer(layerCur, block, inVar, {outVar},{});
inVar = outVar;
blockNum = blockNum + 1;
end
% Add a sum layer
function [net, inVar, blockNum] = addSum(net, blockNum, inVar)
outVar = sprintf('sum%d', blockNum);
layerCur = sprintf('sum%d', blockNum);
block = dagnn.Sum();
net.addLayer(layerCur, block, inVar, {outVar},{});
inVar = outVar;
blockNum = blockNum + 1;
end
% Add a relu layer
function [net, inVar, blockNum] = addReLU(net, blockNum, inVar)
outVar = sprintf('relu%d', blockNum);
layerCur = sprintf('relu%d', blockNum);
block = dagnn.ReLU('leak',0);
net.addLayer(layerCur, block, {inVar}, {outVar},{});
inVar = outVar;
blockNum = blockNum + 1;
end
% Add a bnorm layer
function [net, inVar, blockNum] = addBnorm(net, blockNum, inVar, n_ch)
trainMethod = 'adam';
outVar = sprintf('bnorm%d', blockNum);
layerCur = sprintf('bnorm%d', blockNum);
params={[layerCur '_g'], [layerCur '_b'], [layerCur '_m']};
net.addLayer(layerCur, dagnn.BatchNorm('numChannels', n_ch), {inVar}, {outVar},params) ;
pidx = net.getParamIndex({[layerCur '_g'], [layerCur '_b'], [layerCur '_m']});
b_min = 0.025;
net.params(pidx(1)).value = clipping(sqrt(2/(9*n_ch))*randn(n_ch,1,'single'),b_min);
net.params(pidx(1)).learningRate= 1;
net.params(pidx(1)).weightDecay = 0;
net.params(pidx(1)).trainMethod = trainMethod;
net.params(pidx(2)).value = zeros(n_ch, 1, 'single');
net.params(pidx(2)).learningRate= 1;
net.params(pidx(2)).weightDecay = 0;
net.params(pidx(2)).trainMethod = trainMethod;
net.params(pidx(3)).value = [zeros(n_ch,1,'single'), 0.01*ones(n_ch,1,'single')];
net.params(pidx(3)).learningRate= 1;
net.params(pidx(3)).weightDecay = 0;
net.params(pidx(3)).trainMethod = 'average';
inVar = outVar;
blockNum = blockNum + 1;
end
% add a ConvTranspose layer
function [net, inVar, blockNum] = addConvt(net, blockNum, inVar, dims, crop, upsample, lr)
opts.cudnnWorkspaceLimit = 1024*1024*1024*2; % 2GB
convOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ;
trainMethod = 'adam';
outVar = sprintf('convt%d', blockNum);
layerCur = sprintf('convt%d', blockNum);
convBlock = dagnn.ConvTranspose('size', dims, 'crop', crop,'upsample', upsample, ...
'hasBias', true, 'opts', convOpts);
net.addLayer(layerCur, convBlock, {inVar}, {outVar},{[layerCur '_f'], [layerCur '_b']});
f = net.getParamIndex([layerCur '_f']) ;
sc = sqrt(2/(dims(1)*dims(2)*dims(4))) ; %improved Xavier
net.params(f).value = sc*randn(dims, 'single');
net.params(f).learningRate = lr(1);
net.params(f).weightDecay = 1;
net.params(f).trainMethod = trainMethod;
f = net.getParamIndex([layerCur '_b']) ;
net.params(f).value = zeros(dims(3), 1, 'single');
net.params(f).learningRate = lr(2);
net.params(f).weightDecay = 1;
net.params(f).trainMethod = trainMethod;
inVar = outVar;
blockNum = blockNum + 1;
end
% add a Conv layer
function [net, inVar, blockNum] = addConv(net, blockNum, inVar, dims, pad, stride, lr)
opts.cudnnWorkspaceLimit = 1024*1024*1024*2; % 2GB
convOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ;
trainMethod = 'adam';
outVar = sprintf('conv%d', blockNum);
layerCur = sprintf('conv%d', blockNum);
convBlock = dagnn.Conv('size', dims, 'pad', pad,'stride', stride, ...
'hasBias', true, 'opts', convOpts);
net.addLayer(layerCur, convBlock, {inVar}, {outVar},{[layerCur '_f'], [layerCur '_b']});
f = net.getParamIndex([layerCur '_f']) ;
sc = sqrt(2/(dims(1)*dims(2)*max(dims(3), dims(4)))) ; %improved Xavier
net.params(f).value = sc*randn(dims, 'single') ;
net.params(f).learningRate = lr(1);
net.params(f).weightDecay = 1;
net.params(f).trainMethod = trainMethod;
f = net.getParamIndex([layerCur '_b']) ;
net.params(f).value = zeros(dims(4), 1, 'single');
net.params(f).learningRate = lr(2);
net.params(f).weightDecay = 1;
net.params(f).trainMethod = trainMethod;
inVar = outVar;
blockNum = blockNum + 1;
end
function A = clipping(A,b)
A(A>=0&A<b) = b;
A(A<0&A>-b) = -b;
end
|
github | cszn/DnCNN-master | DnCNN_train_dag.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_DagNN_v1.1/DnCNN_train_dag.m | 18,129 | utf_8 | 97d9e7711f5ea677436f0f6476a94755 | function [net,stats] = DnCNN_train_dag(net, varargin)
%CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper
% CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with
% the DagNN wrapper instead of the SimpleNN wrapper.
% Copyright (C) 2014-16 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
%%%-------------------------------------------------------------------------
%%% solvers: SGD(default) and Adam with(default)/without gradientClipping
%%%-------------------------------------------------------------------------
%%% solver: Adam
%%% opts.solver = 'Adam';
opts.beta1 = 0.9;
opts.beta2 = 0.999;
opts.alpha = 0.01;
opts.epsilon = 1e-8;
%%% solver: SGD
opts.solver = 'SGD';
opts.learningRate = 0.01;
opts.weightDecay = 0.0005;
opts.momentum = 0.9 ;
%%% GradientClipping
opts.gradientClipping = false;
opts.theta = 0.005;
%%%-------------------------------------------------------------------------
%%% setting for dag
%%%-------------------------------------------------------------------------
opts.conserveMemory = true;
opts.mode = 'normal';
opts.cudnn = true ;
opts.backPropDepth = +inf ;
opts.skipForward = false;
opts.numSubBatches = 1;
%%%-------------------------------------------------------------------------
%%% setting for model
%%%-------------------------------------------------------------------------
opts.batchSize = 128 ;
opts.gpus = [];
opts.numEpochs = 300 ;
opts.modelName = 'model';
opts.expDir = fullfile('data',opts.modelName) ;
opts.numberImdb = 1;
opts.imdbDir = opts.expDir;
opts.derOutputs = {'objective', 1} ;
%%%-------------------------------------------------------------------------
%%% update settings
%%%-------------------------------------------------------------------------
opts = vl_argparse(opts, varargin);
opts.numEpochs = numel(opts.learningRate);
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
%%% load training data
% opts.imdbPath = fullfile(opts.imdbDir, 'imdb.mat');
% imdb = load(opts.imdbPath) ;
% if mod(epoch,5)~=1 && isfield(imdb,'set') ~= 0
%
% else
% clear imdb;
% [imdb] = generatepatches;
% end
%
% opts.train = find(imdb.set==1);
opts.continue = true;
opts.prefetch = true;
opts.saveMomentum = false;
opts.nesterovUpdate = false ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.extractStatsFn = @extractStats ;
opts = vl_argparse(opts, varargin) ;
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
opts.train = true;
evaluateMode = isempty(opts.train) ;
% -------------------------------------------------------------------------
% Train
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf([opts.modelName,'-epoch-%d.mat'], ep));
start = findLastCheckpoint(opts.expDir,opts.modelName) ;
if start>=1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net] = loadState(modelPath(start)) ;
end
state = [] ;
% for iobj = numel(opts.derOutputs)
net.vars(net.getVarIndex(opts.derOutputs{1})).precious = 1;
% end
imdb = [];
for epoch=start+1:opts.numEpochs
if mod(epoch,10)~=1 && isfield(imdb,'set') ~= 0
else
clear imdb;
[imdb] = generatepatches;
end
opts.train = find(imdb.set==1);
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.thetaCurrent = opts.theta(min(epoch, numel(opts.theta)));
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.getBatch = getBatch ;
if numel(opts.gpus) <= 1
[net,~] = processEpoch(net, state, params, 'train',imdb) ;
if ~evaluateMode
saveState(modelPath(epoch), net) ;
end
% lastStats = state.stats ;
else
spmd
[net, ~] = processEpoch(net, state, params, 'train',imdb) ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net) ;
end
% lastStats = state.stats ;
end
%lastStats = accumulateStats(lastStats) ;
end
% stats.train(epoch) = lastStats.train ;
% stats.val(epoch) = lastStats.val ;
% clear lastStats ;
% saveStats(modelPath(epoch), stats) ;
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode, imdb)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
state.momentum = num2cell(zeros(1, numel(net.params))) ;
state.m = num2cell(zeros(1, numel(net.params))) ;
state.v = num2cell(zeros(1, numel(net.params))) ;
state.t = num2cell(zeros(1, numel(net.params))) ;
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net.move('gpu') ;
state.momentum = cellfun(@gpuArray, state.momentum, 'uniformoutput', false) ;
state.m = cellfun(@gpuArray,state.m,'UniformOutput',false) ;
state.v = cellfun(@gpuArray,state.v,'UniformOutput',false) ;
state.t = cellfun(@gpuArray,state.t,'UniformOutput',false) ;
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
net.setParameterServer(parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
num = 0 ;
epoch = params.epoch ;
subset = params.(mode) ;
%adjustTime = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
count = 0;
%start = tic ;
for t=1:params.batchSize:numel(subset)
% fprintf('%s: epoch %02d: %3d/%3d:', mode, epoch, ...
% fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
count = count + 1;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
inputs = params.getBatch(imdb, batch) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(imdb, nextBatch) ;
end
if strcmp(mode, 'train')
net.mode = 'normal' ;
net.accumulateParamDers = (s ~= 1) ;
net.eval(inputs, params.derOutputs, 'holdOn', s < params.numSubBatches) ;
else
net.mode = 'test' ;
net.eval(inputs) ;
end
end
% Accumulate gradient.
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
state = accumulateGradients(net, state, params, batchSize, parserv) ;
end
%%%--------add your code here------------------------
%%%--------------------------------------------------
loss2 = squeeze(gather(net.vars(net.getVarIndex(params.derOutputs{1})).value));
fprintf('%s: epoch %02d : %3d/%3d:', mode, epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
fprintf('error: %f \n', loss2) ;
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
state.m = [] ;
state.v = [] ;
state.t = [] ;
else
state.momentum = cellfun(@gather, state.momentum, 'uniformoutput', false) ;
state.m = cellfun(@gather, state.m, 'uniformoutput', false) ;
state.v = cellfun(@gather, state.v, 'uniformoutput', false) ;
state.t = cellfun(@gather, state.t, 'uniformoutput', false) ;
end
net.reset() ;
net.move('cpu') ;
% -------------------------------------------------------------------------
function state = accumulateGradients(net, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
% numGpus = numel(params.gpus) ;
% otherGpus = setdiff(1:numGpus, labindex) ;
for p=1:numel(net.params)
if ~isempty(parserv)
parDer = parserv.pullWithIndex(p) ;
else
parDer = net.params(p).der ;
end
switch params.solver
case 'SGD' %%% solver: SGD
switch net.params(p).trainMethod
case 'average' % mainly for batch normalization
thisLR = net.params(p).learningRate;
net.params(p).value = vl_taccum(...
1 - thisLR, net.params(p).value, ...
(thisLR/batchSize/net.params(p).fanout), parDer) ;
otherwise
thisDecay = params.weightDecay * net.params(p).weightDecay ;
thisLR = params.learningRate * net.params(p).learningRate ;
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.params(p).value) ;
theta = params.thetaCurrent/lr;
parDer = gradientClipping(parDer,theta,params.gradientClipping);
% Update momentum.
state.momentum{p} = vl_taccum(...
params.momentum, state.momentum{p}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = vl_taccum(...
params.momentum, state.momentum{p}, ...
-1, parDer) ;
else
delta = state.momentum{p} ;
end
% Update parameters.
net.params(p).value = vl_taccum(...
1, net.params(p).value, thisLR, delta) ;
end
case 'Adam'
switch net.params(p).trainMethod
case 'average' % mainly for batch normalization
thisLR = net.params(p).learningRate;
net.params(p).value = vl_taccum(...
1 - thisLR, net.params(p).value, ...
(thisLR/batchSize/net.params(p).fanout), parDer) ;
otherwise
thisLR = params.learningRate * net.params(p).learningRate ;
state.t{p} = state.t{p} + 1;
t = state.t{p};
alpha = thisLR; % opts.alpha;
lr = alpha * sqrt(1 - params.beta2^t) / (1 - params.beta1^t);
state.m{p} = state.m{p} + (1 - params.beta1) .* (net.params(p).der - state.m{p});
state.v{p} = state.v{p} + (1 - params.beta2) .* (net.params(p).der .* net.params(p).der - state.v{p});
net.params(p).value = net.params(p).value - lr * state.m{p} ./ (sqrt(state.v{p}) + params.epsilon);% - thisLR * 0.0005 * net.params(p).value;
end
end
end
%%%-------------------------------------------------------------------------
function A = smallClipping(A, theta)
%%%-------------------------------------------------------------------------
A(A>theta) = A(A>theta) -0.0001;
A(A<-theta) = A(A<-theta)+0.0001;
%%%-------------------------------------------------------------------------
function A = smallClipping2(A, theta1,theta2)
%%%-------------------------------------------------------------------------
A(A>theta1) = A(A>theta1)-0.02;
A(A<theta2) = A(A<theta2)+0.02;
function A = smallClipping3(A, theta1,theta2)
%%%-------------------------------------------------------------------------
A(A>theta1) = A(A>theta1) -0.1;
A(A<theta2) = A(A<theta2) +0.1;
% % -------------------------------------------------------------------------
% function stats = accumulateStats(stats_)
% % -------------------------------------------------------------------------
%
% for s = {'train', 'val'}
% s = char(s) ;
% total = 0 ;
%
% % initialize stats stucture with same fields and same order as
% % stats_{1}
% stats__ = stats_{1} ;
% names = fieldnames(stats__.(s))' ;
% values = zeros(1, numel(names)) ;
% fields = cat(1, names, num2cell(values)) ;
% stats.(s) = struct(fields{:}) ;
%
% for g = 1:numel(stats_)
% stats__ = stats_{g} ;
% num__ = stats__.(s).num ;
% total = total + num__ ;
%
% for f = setdiff(fieldnames(stats__.(s))', 'num')
% f = char(f) ;
% stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
%
% if g == numel(stats_)
% stats.(s).(f) = stats.(s).(f) / total ;
% end
% end
% end
% stats.(s).num = total ;
% end
% -------------------------------------------------------------------------
function stats = extractStats(stats, net)
% -------------------------------------------------------------------------
sel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ;
for i = 1:numel(sel)
stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net_)
% -------------------------------------------------------------------------
net = net_.saveobj() ;
save(fileName, 'net') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net') ;
net = dagnn.DagNN.loadobj(net) ;
% if isempty(whos('stats'))
% error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
% fileName) ;
% end
%%%-------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir,modelName)
%%%-------------------------------------------------------------------------
list = dir(fullfile(modelDir, [modelName,'-epoch-*.mat'])) ;
tokens = regexp({list.name}, [modelName,'-epoch-([\d]+).mat'], 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename)
clearMex() ;
if numGpus == 1
gpuDevice(opts.gpus)
else
spmd
clearMex() ;
gpuDevice(opts.gpus(labindex))
end
end
end
%%%-------------------------------------------------------------------------
function A = gradientClipping(A, theta,gradientClip)
%%%-------------------------------------------------------------------------
if gradientClip
A(A>theta) = theta;
A(A<-theta) = -theta;
else
return;
end
% -------------------------------------------------------------------------
function fn = getBatch()
% -------------------------------------------------------------------------
fn = @(x,y) getDagNNBatch(x,y) ;
% -------------------------------------------------------------------------
function [inputs2] = getDagNNBatch(imdb, batch)
% -------------------------------------------------------------------------
noiselevel = 25;
label = imdb.labels(:,:,:,batch);
label = data_augmentation(label,randi(8));
input = label + noiselevel/255*randn(size(label),'single'); % add AWGN with noise level noiselevel
input = gpuArray(input);
label = gpuArray(label);
inputs2 = {'input', input, 'label', label} ;
|
github | cszn/DnCNN-master | Cal_PSNRSSIM.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_DagNN_v1.1/utilities/Cal_PSNRSSIM.m | 6,569 | utf_8 | c726759a14c4754004b2fbbec4ebbf36 | function [psnr_cur, ssim_cur] = Cal_PSNRSSIM(A,B,row,col)
[n,m,ch]=size(B);
A = A(row+1:n-row,col+1:m-col,:);
B = B(row+1:n-row,col+1:m-col,:);
A=double(A); % Ground-truth
B=double(B); %
e=A(:)-B(:);
mse=mean(e.^2);
psnr_cur=10*log10(255^2/mse);
if ch==1
[ssim_cur, ~] = ssim_index(A, B);
else
ssim_cur = (ssim_index(A(:,:,1), B(:,:,1)) + ssim_index(A(:,:,2), B(:,:,2)) + ssim_index(A(:,:,3), B(:,:,3)))/3;
end
function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L)
%========================================================================
%SSIM Index, Version 1.0
%Copyright(c) 2003 Zhou Wang
%All Rights Reserved.
%
%The author is with Howard Hughes Medical Institute, and Laboratory
%for Computational Vision at Center for Neural Science and Courant
%Institute of Mathematical Sciences, New York University.
%
%----------------------------------------------------------------------
%Permission to use, copy, or modify this software and its documentation
%for educational and research purposes only and without fee is hereby
%granted, provided that this copyright notice and the original authors'
%names appear on all copies and supporting documentation. This program
%shall not be used, rewritten, or adapted as the basis of a commercial
%software or hardware product without first obtaining permission of the
%authors. The authors make no representations about the suitability of
%this software for any purpose. It is provided "as is" without express
%or implied warranty.
%----------------------------------------------------------------------
%
%This is an implementation of the algorithm for calculating the
%Structural SIMilarity (SSIM) index between two images. Please refer
%to the following paper:
%
%Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image
%quality assessment: From error measurement to structural similarity"
%IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004.
%
%Kindly report any suggestions or corrections to [email protected]
%
%----------------------------------------------------------------------
%
%Input : (1) img1: the first image being compared
% (2) img2: the second image being compared
% (3) K: constants in the SSIM index formula (see the above
% reference). defualt value: K = [0.01 0.03]
% (4) window: local window for statistics (see the above
% reference). default widnow is Gaussian given by
% window = fspecial('gaussian', 11, 1.5);
% (5) L: dynamic range of the images. default: L = 255
%
%Output: (1) mssim: the mean SSIM index value between 2 images.
% If one of the images being compared is regarded as
% perfect quality, then mssim can be considered as the
% quality measure of the other image.
% If img1 = img2, then mssim = 1.
% (2) ssim_map: the SSIM index map of the test image. The map
% has a smaller size than the input images. The actual size:
% size(img1) - size(window) + 1.
%
%Default Usage:
% Given 2 test images img1 and img2, whose dynamic range is 0-255
%
% [mssim ssim_map] = ssim_index(img1, img2);
%
%Advanced Usage:
% User defined parameters. For example
%
% K = [0.05 0.05];
% window = ones(8);
% L = 100;
% [mssim ssim_map] = ssim_index(img1, img2, K, window, L);
%
%See the results:
%
% mssim %Gives the mssim value
% imshow(max(0, ssim_map).^4) %Shows the SSIM index map
%
%========================================================================
if (nargin < 2 || nargin > 5)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5); %
K(1) = 0.01; % default settings
K(2) = 0.03; %
L = 255; %
end
if (nargin == 3)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5);
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 5)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
C1 = (K(1)*L)^2;
C2 = (K(2)*L)^2;
window = window/sum(sum(window));
img1 = double(img1);
img2 = double(img2);
mu1 = filter2(window, img1, 'valid');
mu2 = filter2(window, img2, 'valid');
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;
if (C1 > 0 & C2 > 0)
ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
else
numerator1 = 2*mu1_mu2 + C1;
numerator2 = 2*sigma12 + C2;
denominator1 = mu1_sq + mu2_sq + C1;
denominator2 = sigma1_sq + sigma2_sq + C2;
ssim_map = ones(size(mu1));
index = (denominator1.*denominator2 > 0);
ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));
index = (denominator1 ~= 0) & (denominator2 == 0);
ssim_map(index) = numerator1(index)./denominator1(index);
end
mssim = mean2(ssim_map);
return
|
github | cszn/DnCNN-master | Demo_DagNN_Merge_Bnorm.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_DagNN_v1.1/utilities/Demo_DagNN_Merge_Bnorm.m | 6,930 | utf_8 | 2d9818396cfb748ea1134a8b04e11426 | function [] = Demo_DagNN_Merge_Bnorm()
% merge bnorm: 'DnCNN-epoch-50.mat' ------> 'DnCNN-epoch-0.mat'
inputfileName = 'DnCNN-epoch-50.mat';
targetfileName = 'DnCNN-epoch-0.mat';
% Merge Bnorm to (1) accelerate the testing inference; and (2) fine-tune the model with small learning rate for better PSNR.
load(inputfileName);
net = dagnn.DagNN.loadobj(net) ;
%CNN_IMAGENET_DEPLOY Deploy a CNN
isDag = isa(net, 'dagnn.DagNN');
% if isDag
% dagRemoveLayersOfType(net, 'dagnn.Loss') ;
% dagRemoveLayersOfType(net, 'dagnn.DropOut') ;
% else
% net = simpleRemoveLayersOfType(net, 'softmaxloss') ;
% net = simpleRemoveLayersOfType(net, 'dropout') ;
% end
if isDag
dagMergeBatchNorm(net) ;
dagRemoveLayersOfType(net, 'dagnn.BatchNorm') ;
else
net = simpleMergeBatchNorm(net) ;
net = simpleRemoveLayersOfType(net, 'bnorm') ;
end
net = net.saveobj() ;
save(targetfileName, 'net') ;
% Switch to use MatConvNet default memory limit for CuDNN (512 MB)
% if ~isDag
% for l = simpleFindLayersOfType(net, 'conv')
% net.layers{l}.opts = removeCuDNNMemoryLimit(net.layers{l}.opts) ;
% end
% else
% for name = dagFindLayersOfType(net, 'dagnn.Conv')
% l = net.getLayerIndex(char(name)) ;
% net.layers(l).block.opts = removeCuDNNMemoryLimit(net.layers(l).block.opts) ;
% end
% end
% -------------------------------------------------------------------------
function opts = removeCuDNNMemoryLimit(opts)
% -------------------------------------------------------------------------
remove = false(1, numel(opts)) ;
for i = 1:numel(opts)
if isstr(opts{i}) && strcmp(lower(opts{i}), 'CudnnWorkspaceLimit')
remove([i i+1]) = true ;
end
end
opts = opts(~remove) ;
% -------------------------------------------------------------------------
function net = simpleRemoveMomentum(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if isfield(net.layers{l}, 'momentum')
net.layers{l} = rmfield(net.layers{l}, 'momentum') ;
end
end
% -------------------------------------------------------------------------
function layers = simpleFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = find(cellfun(@(x)strcmp(x.type, type), net.layers)) ;
% -------------------------------------------------------------------------
function net = simpleRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = simpleFindLayersOfType(net, type) ;
net.layers(layers) = [] ;
% -------------------------------------------------------------------------
function layers = dagFindLayersWithOutput(net, outVarName)
% -------------------------------------------------------------------------
layers = {} ;
for l = 1:numel(net.layers)
if any(strcmp(net.layers(l).outputs, outVarName))
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function layers = dagFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = [] ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, type)
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function dagRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, type) ;
for i = 1:numel(names)
layer = net.layers(net.getLayerIndex(names{i})) ;
net.removeLayer(names{i}) ;
net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;
end
% -------------------------------------------------------------------------
function dagMergeBatchNorm(net)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, 'dagnn.BatchNorm') ;
for name = names
name = char(name) ;
layer = net.layers(net.getLayerIndex(name)) ;
% merge into previous conv layer
playerName = dagFindLayersWithOutput(net, layer.inputs{1}) ;
playerName = playerName{1} ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
if ~isa(player.block, 'dagnn.Conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
% if the convolution layer does not have a bias,
% recreate it to have one
if ~player.block.hasBias
block = player.block ;
block.hasBias = true ;
net.renameLayer(playerName, 'tmp') ;
net.addLayer(playerName, ...
block, ...
player.inputs, ...
player.outputs, ...
{player.params{1}, sprintf('%s_b',playerName)}) ;
net.removeLayer('tmp') ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
biases = net.getParamIndex(player.params{2}) ;
net.params(biases).value = zeros(block.size(4), 1, 'single') ;
end
filters = net.getParamIndex(player.params{1}) ;
biases = net.getParamIndex(player.params{2}) ;
multipliers = net.getParamIndex(layer.params{1}) ;
offsets = net.getParamIndex(layer.params{2}) ;
moments = net.getParamIndex(layer.params{3}) ;
[filtersValue, biasesValue] = mergeBatchNorm(...
net.params(filters).value, ...
net.params(biases).value, ...
net.params(multipliers).value, ...
net.params(offsets).value, ...
net.params(moments).value) ;
net.params(filters).value = filtersValue ;
net.params(biases).value = biasesValue ;
net.params(biases).learningRate = 1;
end
% -------------------------------------------------------------------------
function net = simpleMergeBatchNorm(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if strcmp(net.layers{l}.type, 'bnorm')
if ~strcmp(net.layers{l-1}.type, 'conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
[filters, biases] = mergeBatchNorm(...
net.layers{l-1}.weights{1}, ...
net.layers{l-1}.weights{2}, ...
net.layers{l}.weights{1}, ...
net.layers{l}.weights{2}, ...
net.layers{l}.weights{3}) ;
net.layers{l-1}.weights = {filters, biases} ;
end
f = net.getParamIndex(net.layers{l-1}.params) ;
net.params(f(2)).learningRate = 1;
end
% -------------------------------------------------------------------------
function [filters, biases] = mergeBatchNorm(filters, biases, multipliers, offsets, moments)
% -------------------------------------------------------------------------
% wk / sqrt(sigmak^2 + eps)
% bk - wk muk / sqrt(sigmak^2 + eps)
a = multipliers(:) ./ moments(:,2) ;
b = offsets(:) - moments(:,1) .* a ;
biases(:) = biases(:) + b(:) ;
sz = size(filters) ;
numFilters = sz(4) ;
filters = reshape(bsxfun(@times, reshape(filters, [], numFilters), a'), sz) ;
|
github | cszn/DnCNN-master | DnCNN_init_model_64_25_Res_Bnorm_Adam.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_v1.1/DnCNN_init_model_64_25_Res_Bnorm_Adam.m | 1,705 | utf_8 | fc6fb32e289c615f4b7d2cbedcba8be6 |
function net = DnCNN_init_model_64_25_Res_Bnorm_Adam
%%% 17 layers
b_min = 0.025;
lr11 = [1 1];
lr10 = [1 0];
weightDecay = [1 0];
meanvar = [zeros(64,1,'single'), 0.01*ones(64,1,'single')];
% Define network
net.layers = {} ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{sqrt(2/(9*64))*randn(3,3,1,64,'single'), zeros(64,1,'single')}}, ...
'stride', 1, ...
'pad', 1, ...
'dilate',1, ...
'learningRate',lr11, ...
'weightDecay',weightDecay, ...
'opts',{{}}) ;
net.layers{end+1} = struct('type', 'relu','leak',0) ;
for i = 1:1:15
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{sqrt(2/(9*64))*randn(3,3,64,64,'single'), zeros(64,1,'single')}}, ...
'stride', 1, ...
'learningRate',lr10, ...
'dilate',1, ...
'weightDecay',weightDecay, ...
'pad', 1, 'opts', {{}}) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{clipping(sqrt(2/(9*64))*randn(64,1,'single'),b_min), zeros(64,1,'single'),meanvar}}, ...
'learningRate', [1 1 1], ...
'weightDecay', [0 0], ...
'opts', {{}}) ;
net.layers{end+1} = struct('type', 'relu','leak',0) ;
end
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{sqrt(2/(9*64))*randn(3,3,64,1,'single'), zeros(1,1,'single')}}, ...
'stride', 1, ...
'learningRate',lr11, ...
'dilate',1, ...
'weightDecay',weightDecay, ...
'pad', 1, 'opts', {{}}) ;
net.layers{end+1} = struct('type', 'loss') ; % make sure the new 'vl_nnloss.m' is in the same folder.
% Fill in default values
net = vl_simplenn_tidy(net);
function A = clipping(A,b)
A(A>=0&A<b) = b;
A(A<0&A>-b) = -b;
|
github | cszn/DnCNN-master | DnCNN_train.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_v1.1/DnCNN_train.m | 12,685 | utf_8 | d664f407bd2a6d0711394366d701cebf | function [net, state] = DnCNN_train(net, varargin)
% The function automatically restarts after each training epoch by
% checkpointing.
%
% The function supports training on CPU or on one or more GPUs
% (specify the list of GPU IDs in the `gpus` option).
% Copyright (C) 2014-16 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
%%%-------------------------------------------------------------------------
%%% solvers: SGD(default) and Adam with(default)/without gradientClipping
%%%-------------------------------------------------------------------------
%%% solver: Adam
%%% opts.solver = 'Adam';
opts.beta1 = 0.9;
opts.beta2 = 0.999;
opts.alpha = 0.01;
opts.epsilon = 1e-8;
%%% solver: SGD
opts.solver = 'SGD';
opts.learningRate = 0.01;
opts.weightDecay = 0.001;
opts.momentum = 0.9 ;
%%% GradientClipping
opts.gradientClipping = false;
opts.theta = 0.005;
%%% specific parameter for Bnorm
opts.bnormLearningRate = 0;
%%%-------------------------------------------------------------------------
%%% setting for simplenn
%%%-------------------------------------------------------------------------
opts.conserveMemory = true;
opts.mode = 'normal';
opts.cudnn = true ;
opts.backPropDepth = +inf ;
opts.skipForward = false;
opts.numSubBatches = 1;
%%%-------------------------------------------------------------------------
%%% setting for model
%%%-------------------------------------------------------------------------
opts.batchSize = 128 ;
opts.gpus = [];
opts.numEpochs = 300 ;
opts.modelName = 'model';
opts.expDir = fullfile('data',opts.modelName) ;
opts.numberImdb = 1;
opts.imdbDir = opts.expDir;
%%%-------------------------------------------------------------------------
%%% update settings
%%%-------------------------------------------------------------------------
opts = vl_argparse(opts, varargin);
opts.numEpochs = numel(opts.learningRate);
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
%%%-------------------------------------------------------------------------
%%% Initialization
%%%-------------------------------------------------------------------------
net = vl_simplenn_tidy(net); %%% fill in some eventually missing values
net.layers{end-1}.precious = 1;
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
state.getBatch = getBatch ;
%%%-------------------------------------------------------------------------
%%% Train and Test
%%%-------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf([opts.modelName,'-epoch-%d.mat'], ep));
start = findLastCheckpoint(opts.expDir,opts.modelName) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d', mfilename, start) ;
load(modelPath(start), 'net') ;
net = vl_simplenn_tidy(net) ;
end
%%% load training data
opts.imdbPath = fullfile(opts.imdbDir);
imdb = load(opts.imdbPath) ;
opts.train = find(imdb.set==1);
for epoch = start+1 : opts.numEpochs
%%% Train for one epoch.
state.epoch = epoch ;
state.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate)));
opts.thetaCurrent = opts.theta(min(epoch, numel(opts.theta)));
if numel(opts.gpus) == 1
net = vl_simplenn_move(net, 'gpu') ;
end
state.train = opts.train(randperm(numel(opts.train))) ; %%% shuffle
[net, state] = process_epoch(net, state, imdb, opts, 'train');
net.layers{end}.class =[];
net = vl_simplenn_move(net, 'cpu');
%%% save current model
save(modelPath(epoch), 'net')
end
%%%-------------------------------------------------------------------------
function [net, state] = process_epoch(net, state, imdb, opts, mode)
%%%-------------------------------------------------------------------------
if strcmp(mode,'train')
switch opts.solver
case 'SGD' %%% solver: SGD
for i = 1:numel(net.layers)
if isfield(net.layers{i}, 'weights')
for j = 1:numel(net.layers{i}.weights)
state.layers{i}.momentum{j} = 0;
end
end
end
case 'Adam' %%% solver: Adam
for i = 1:numel(net.layers)
if isfield(net.layers{i}, 'weights')
for j = 1:numel(net.layers{i}.weights)
state.layers{i}.t{j} = 0;
state.layers{i}.m{j} = 0;
state.layers{i}.v{j} = 0;
end
end
end
end
end
subset = state.(mode) ;
num = 0 ;
res = [];
for t=1:opts.batchSize:numel(subset)
for s=1:opts.numSubBatches
% get this image batch
batchStart = t + (s-1);
batchEnd = min(t+opts.batchSize-1, numel(subset)) ;
batch = subset(batchStart : opts.numSubBatches : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
[inputs,labels] = state.getBatch(imdb, batch) ;
if numel(opts.gpus) == 1
inputs = gpuArray(inputs);
labels = gpuArray(labels);
end
if strcmp(mode, 'train')
dzdy = single(1);
evalMode = 'normal';%%% forward and backward (Gradients)
else
dzdy = [] ;
evalMode = 'test'; %%% forward only
end
net.layers{end}.class = labels ;
res = vl_simplenn(net, inputs, dzdy, res, ...
'accumulate', s ~= 1, ...
'mode', evalMode, ...
'conserveMemory', opts.conserveMemory, ...
'backPropDepth', opts.backPropDepth, ...
'cudnn', opts.cudnn) ;
end
if strcmp(mode, 'train')
[state, net] = params_updates(state, net, res, opts, opts.batchSize) ;
end
lossL2 = gather(res(end).x) ;
%%%--------add your code here------------------------
%%%--------------------------------------------------
fprintf('%s: epoch %02d dataset %02d: %3d/%3d:', mode, state.epoch, mod(state.epoch,opts.numberImdb), ...
fix((t-1)/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ;
fprintf('error: %f \n', lossL2) ;
end
%%%-------------------------------------------------------------------------
function [state, net] = params_updates(state, net, res, opts, batchSize)
%%%-------------------------------------------------------------------------
switch opts.solver
case 'SGD' %%% solver: SGD
for l=numel(net.layers):-1:1
for j=1:numel(res(l).dzdw)
if j == 3 && strcmp(net.layers{l}.type, 'bnorm')
%%% special case for learning bnorm moments
thisLR = net.layers{l}.learningRate(j) - opts.bnormLearningRate;
net.layers{l}.weights{j} = vl_taccum(...
1 - thisLR, ...
net.layers{l}.weights{j}, ...
thisLR / batchSize, ...
res(l).dzdw{j}) ;
else
thisDecay = opts.weightDecay * net.layers{l}.weightDecay(j);
thisLR = state.learningRate * net.layers{l}.learningRate(j);
if opts.gradientClipping
theta = opts.thetaCurrent/thisLR;
state.layers{l}.momentum{j} = opts.momentum * state.layers{l}.momentum{j} ...
- thisDecay * net.layers{l}.weights{j} ...
- (1 / batchSize) * gradientClipping(res(l).dzdw{j},theta) ;
net.layers{l}.weights{j} = net.layers{l}.weights{j} + ...
thisLR * state.layers{l}.momentum{j} ;
else
state.layers{l}.momentum{j} = opts.momentum * state.layers{l}.momentum{j} ...
- thisDecay * net.layers{l}.weights{j} ...
- (1 / batchSize) * res(l).dzdw{j} ;
net.layers{l}.weights{j} = net.layers{l}.weights{j} + ...
thisLR * state.layers{l}.momentum{j} ;
end
end
end
end
case 'Adam' %%% solver: Adam
for l=numel(net.layers):-1:1
for j=1:numel(res(l).dzdw)
if j == 3 && strcmp(net.layers{l}.type, 'bnorm')
%%% special case for learning bnorm moments
thisLR = net.layers{l}.learningRate(j) - opts.bnormLearningRate;
net.layers{l}.weights{j} = vl_taccum(...
1 - thisLR, ...
net.layers{l}.weights{j}, ...
thisLR / batchSize, ...
res(l).dzdw{j}) ;
else
thisLR = state.learningRate * net.layers{l}.learningRate(j);
state.layers{l}.t{j} = state.layers{l}.t{j} + 1;
t = state.layers{l}.t{j};
alpha = thisLR;
lr = alpha * sqrt(1 - opts.beta2^t) / (1 - opts.beta1^t);
state.layers{l}.m{j} = state.layers{l}.m{j} + (1 - opts.beta1) .* (res(l).dzdw{j} - state.layers{l}.m{j});
state.layers{l}.v{j} = state.layers{l}.v{j} + (1 - opts.beta2) .* (res(l).dzdw{j} .* res(l).dzdw{j} - state.layers{l}.v{j});
if opts.gradientClipping
theta = opts.thetaCurrent/lr;
net.layers{l}.weights{j} = net.layers{l}.weights{j} - lr * gradientClipping(state.layers{l}.m{j} ./ (sqrt(state.layers{l}.v{j}) + opts.epsilon),theta);
else
net.layers{l}.weights{j} = net.layers{l}.weights{j} - lr * state.layers{l}.m{j} ./ (sqrt(state.layers{l}.v{j}) + opts.epsilon);
end
% net.layers{l}.weights{j} = weightClipping(net.layers{l}.weights{j},2); % gradually clip the weights
end
end
end
end
%%%-------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir,modelName)
%%%-------------------------------------------------------------------------
list = dir(fullfile(modelDir, [modelName,'-epoch-*.mat'])) ;
tokens = regexp({list.name}, [modelName,'-epoch-([\d]+).mat'], 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
%%%-------------------------------------------------------------------------
function A = gradientClipping(A, theta)
%%%-------------------------------------------------------------------------
A(A>theta) = theta;
A(A<-theta) = -theta;
%%%-------------------------------------------------------------------------
function A = weightClipping(A, theta)
%%%-------------------------------------------------------------------------
A(A>theta) = A(A>theta) -0.0005;
A(A<-theta) = A(A<-theta)+0.0005;
%%%-------------------------------------------------------------------------
function fn = getBatch
%%%-------------------------------------------------------------------------
fn = @(x,y) getSimpleNNBatch(x,y);
%%%-------------------------------------------------------------------------
function [inputs,labels] = getSimpleNNBatch(imdb, batch)
%%%-------------------------------------------------------------------------
global sigma;
inputs = imdb.inputs(:,:,:,batch);
rng('shuffle');
mode = randperm(8);
inputs = data_augmentation(inputs, mode(1));
labels = sigma/255*randn(size(inputs),'single');
inputs = inputs + labels;
function image = data_augmentation(image, mode)
if mode == 1
return;
end
if mode == 2 % flipped
image = flipud(image);
return;
end
if mode == 3 % rotation 90
image = rot90(image,1);
return;
end
if mode == 4 % rotation 90 & flipped
image = rot90(image,1);
image = flipud(image);
return;
end
if mode == 5 % rotation 180
image = rot90(image,2);
return;
end
if mode == 6 % rotation 180 & flipped
image = rot90(image,2);
image = flipud(image);
return;
end
if mode == 7 % rotation 270
image = rot90(image,3);
return;
end
if mode == 8 % rotation 270 & flipped
image = rot90(image,3);
image = flipud(image);
return;
end
|
github | cszn/DnCNN-master | Cal_PSNRSSIM.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_v1.1/data/utilities/Cal_PSNRSSIM.m | 6,471 | utf_8 | 1689b76bfd626a066df745e53cf59f19 | function [psnr_cur, ssim_cur] = Cal_PSNRSSIM(A,B,row,col)
[n,m,ch]=size(B);
A = A(row+1:n-row,col+1:m-col,:);
B = B(row+1:n-row,col+1:m-col,:);
A=double(A); % Ground-truth
B=double(B); %
e=A(:)-B(:);
mse=mean(e.^2);
psnr_cur=10*log10(255^2/mse);
if ch==1
[ssim_cur, ~] = ssim_index(A, B);
else
ssim_cur = -1;
end
function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L)
%========================================================================
%SSIM Index, Version 1.0
%Copyright(c) 2003 Zhou Wang
%All Rights Reserved.
%
%The author is with Howard Hughes Medical Institute, and Laboratory
%for Computational Vision at Center for Neural Science and Courant
%Institute of Mathematical Sciences, New York University.
%
%----------------------------------------------------------------------
%Permission to use, copy, or modify this software and its documentation
%for educational and research purposes only and without fee is hereby
%granted, provided that this copyright notice and the original authors'
%names appear on all copies and supporting documentation. This program
%shall not be used, rewritten, or adapted as the basis of a commercial
%software or hardware product without first obtaining permission of the
%authors. The authors make no representations about the suitability of
%this software for any purpose. It is provided "as is" without express
%or implied warranty.
%----------------------------------------------------------------------
%
%This is an implementation of the algorithm for calculating the
%Structural SIMilarity (SSIM) index between two images. Please refer
%to the following paper:
%
%Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image
%quality assessment: From error measurement to structural similarity"
%IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004.
%
%Kindly report any suggestions or corrections to [email protected]
%
%----------------------------------------------------------------------
%
%Input : (1) img1: the first image being compared
% (2) img2: the second image being compared
% (3) K: constants in the SSIM index formula (see the above
% reference). defualt value: K = [0.01 0.03]
% (4) window: local window for statistics (see the above
% reference). default widnow is Gaussian given by
% window = fspecial('gaussian', 11, 1.5);
% (5) L: dynamic range of the images. default: L = 255
%
%Output: (1) mssim: the mean SSIM index value between 2 images.
% If one of the images being compared is regarded as
% perfect quality, then mssim can be considered as the
% quality measure of the other image.
% If img1 = img2, then mssim = 1.
% (2) ssim_map: the SSIM index map of the test image. The map
% has a smaller size than the input images. The actual size:
% size(img1) - size(window) + 1.
%
%Default Usage:
% Given 2 test images img1 and img2, whose dynamic range is 0-255
%
% [mssim ssim_map] = ssim_index(img1, img2);
%
%Advanced Usage:
% User defined parameters. For example
%
% K = [0.05 0.05];
% window = ones(8);
% L = 100;
% [mssim ssim_map] = ssim_index(img1, img2, K, window, L);
%
%See the results:
%
% mssim %Gives the mssim value
% imshow(max(0, ssim_map).^4) %Shows the SSIM index map
%
%========================================================================
if (nargin < 2 || nargin > 5)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5); %
K(1) = 0.01; % default settings
K(2) = 0.03; %
L = 255; %
end
if (nargin == 3)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5);
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 5)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
C1 = (K(1)*L)^2;
C2 = (K(2)*L)^2;
window = window/sum(sum(window));
img1 = double(img1);
img2 = double(img2);
mu1 = filter2(window, img1, 'valid');
mu2 = filter2(window, img2, 'valid');
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;
if (C1 > 0 & C2 > 0)
ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
else
numerator1 = 2*mu1_mu2 + C1;
numerator2 = 2*sigma12 + C2;
denominator1 = mu1_sq + mu2_sq + C1;
denominator2 = sigma1_sq + sigma2_sq + C2;
ssim_map = ones(size(mu1));
index = (denominator1.*denominator2 > 0);
ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));
index = (denominator1 ~= 0) & (denominator2 == 0);
ssim_map(index) = numerator1(index)./denominator1(index);
end
mssim = mean2(ssim_map);
return
|
github | cszn/DnCNN-master | DnCNN_init_model_64_25_Res_Bnorm_Adam.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_v1.0/DnCNN_init_model_64_25_Res_Bnorm_Adam.m | 1,533 | utf_8 | 5cf85b75dfccd48c4d410e7419b73e39 |
function net = DnCNN_init_model_64_25_Res_Bnorm_Adam
%%% 17 layers
lr = [1 1];
lr1 = [1 0];
weightDecay = [1 0];
meanvar = [zeros(64,1,'single'), 0.01*ones(64,1,'single')];
% Define network
net.layers = {} ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{sqrt(2/(9*64))*randn(3,3,1,64,'single'), zeros(64,1,'single')}}, ...
'stride', 1, ...
'pad', 1, ...
'learningRate',lr, ...
'weightDecay',weightDecay, ...
'opts',{{}}) ;
net.layers{end+1} = struct('type', 'relu','leak',0) ;
for i = 1:1:15
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{sqrt(2/(9*64))*randn(3,3,64,64,'single'), zeros(64,1,'single')}}, ...
'stride', 1, ...
'learningRate',lr1, ...
'weightDecay',weightDecay, ...
'pad', 1, 'opts', {{}}) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{sqrt(2/(9*64))*randn(64,1,'single'), zeros(64,1,'single'),meanvar}}, ...
'learningRate', [1 1 1], ...
'weightDecay', [0 0], ...
'opts', {{}}) ;
net.layers{end+1} = struct('type', 'relu','leak',0) ;
end
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{sqrt(2/(9*64))*randn(3,3,64,1,'single'), zeros(1,1,'single')}}, ...
'stride', 1, ...
'learningRate',lr, ...
'weightDecay',weightDecay, ...
'pad', 1, 'opts', {{}}) ;
net.layers{end+1} = struct('type', 'loss') ; % make sure the new 'vl_nnloss.m' is in the same folder.
% Fill in default values
net = vl_simplenn_tidy(net);
|
github | cszn/DnCNN-master | DnCNN_train.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_v1.0/DnCNN_train.m | 10,969 | utf_8 | d6a38316cf04f80bd144c2e9eb06b01f | function [net, state] = DnCNN_train(net, imdb, varargin)
% The function automatically restarts after each training epoch by
% checkpointing.
%
% The function supports training on CPU or on one or more GPUs
% (specify the list of GPU IDs in the `gpus` option).
% Copyright (C) 2014-16 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
%%%-------------------------------------------------------------------------
%%% solvers: SGD(default) and Adam with(default)/without gradientClipping
%%%-------------------------------------------------------------------------
%%% solver: Adam
%%% opts.solver = 'Adam';
opts.beta1 = 0.9;
opts.beta2 = 0.999;
opts.alpha = 0.01;
opts.epsilon = 1e-8;
%%% solver: SGD
opts.solver = 'SGD';
opts.learningRate = 0.01;
opts.weightDecay = 0.0001;
opts.momentum = 0.9 ;
%%% GradientClipping
opts.gradientClipping = false;
opts.theta = 0.005;
%%% specific parameter for Bnorm
opts.bnormLearningRate = 0;
%%%-------------------------------------------------------------------------
%%% setting for simplenn
%%%-------------------------------------------------------------------------
opts.conserveMemory = false ;
opts.mode = 'normal';
opts.cudnn = true ;
opts.backPropDepth = +inf ;
opts.skipForward = false;
%%%-------------------------------------------------------------------------
%%% setting for model
%%%-------------------------------------------------------------------------
opts.batchSize = 128 ;
opts.gpus = [];
opts.numEpochs = 300 ;
opts.modelName = 'model';
opts.expDir = fullfile('data',opts.modelName) ;
opts.train = find(imdb.set==1);
opts.test = find(imdb.set==2);
%%%-------------------------------------------------------------------------
%%% update settings
%%%-------------------------------------------------------------------------
opts = vl_argparse(opts, varargin);
opts.numEpochs = numel(opts.learningRate);
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
%%%-------------------------------------------------------------------------
%%% Initialization
%%%-------------------------------------------------------------------------
net = vl_simplenn_tidy(net); %%% fill in some eventually missing values
net.layers{end-1}.precious = 1;
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
state.getBatch = getBatch ;
%%%-------------------------------------------------------------------------
%%% Train and Test
%%%-------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf([opts.modelName,'-epoch-%d.mat'], ep));
start = findLastCheckpoint(opts.expDir,opts.modelName) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d', mfilename, start) ;
load(modelPath(start), 'net') ;
% net = vl_simplenn_tidy(net) ;
end
for epoch = start+1 : opts.numEpochs
%%% Train for one epoch.
state.epoch = epoch ;
state.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate)));
state.train = opts.train(randperm(numel(opts.train))) ; %%% shuffle
state.test = opts.test; %%% no need to shuffle
opts.thetaCurrent = opts.theta(min(epoch, numel(opts.theta)));
if numel(opts.gpus) == 1
net = vl_simplenn_move(net, 'gpu') ;
end
[net, state] = process_epoch(net, state, imdb, opts, 'train');
[net, ~ ] = process_epoch(net, state, imdb, opts, 'test' );
net = vl_simplenn_move(net, 'cpu');
%%% save current model
save(modelPath(epoch), 'net')
end
%%%-------------------------------------------------------------------------
function [net, state] = process_epoch(net, state, imdb, opts, mode)
%%%-------------------------------------------------------------------------
if strcmp(mode,'train')
switch opts.solver
case 'SGD' %%% solver: SGD
for i = 1:numel(net.layers)
if isfield(net.layers{i}, 'weights')
for j = 1:numel(net.layers{i}.weights)
state.layers{i}.momentum{j} = 0;
end
end
end
case 'Adam' %%% solver: Adam
for i = 1:numel(net.layers)
if isfield(net.layers{i}, 'weights')
for j = 1:numel(net.layers{i}.weights)
state.layers{i}.t{j} = 0;
state.layers{i}.m{j} = 0;
state.layers{i}.v{j} = 0;
end
end
end
end
end
subset = state.(mode) ;
num = 0 ;
res = [];
for t=1:opts.batchSize:numel(subset)
%%% get this image batch
batchStart = t;
batchEnd = min(t+opts.batchSize-1, numel(subset));
batch = subset(batchStart : 1: batchEnd);
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
[inputs,labels] = state.getBatch(imdb, batch) ;
if numel(opts.gpus) == 1
inputs = gpuArray(inputs);
labels = gpuArray(labels);
end
if strcmp(mode, 'train')
dzdy = single(1);
evalMode = 'normal';%%% forward and backward (Gradients)
else
dzdy = [] ;
evalMode = 'test'; %%% forward only
end
net.layers{end}.class = labels ;
res = vl_simplenn(net, inputs, dzdy, res, ...
'mode', evalMode, ...
'conserveMemory', opts.conserveMemory, ...
'backPropDepth', opts.backPropDepth, ...
'cudnn', opts.cudnn) ;
if strcmp(mode, 'train')
[state, net] = params_updates(state, net, res, opts, opts.batchSize) ;
end
lossL2 = gather(res(end).x) ;
%%%--------add your code here------------------------
%%%--------------------------------------------------
fprintf('%s: epoch %02d: %3d/%3d:', mode, state.epoch, ...
fix((t-1)/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ;
fprintf('error: %f \n', lossL2) ;
end
%%%-------------------------------------------------------------------------
function [state, net] = params_updates(state, net, res, opts, batchSize)
%%%-------------------------------------------------------------------------
switch opts.solver
case 'SGD' %%% solver: SGD
for l=numel(net.layers):-1:1
for j=1:numel(res(l).dzdw)
if j == 3 && strcmp(net.layers{l}.type, 'bnorm')
%%% special case for learning bnorm moments
thisLR = net.layers{l}.learningRate(j) - opts.bnormLearningRate;
net.layers{l}.weights{j} = ...
(1 - thisLR) * net.layers{l}.weights{j} + ...
(thisLR/batchSize) * res(l).dzdw{j} ;
else
thisDecay = opts.weightDecay * net.layers{l}.weightDecay(j);
thisLR = state.learningRate * net.layers{l}.learningRate(j);
if opts.gradientClipping
theta = opts.thetaCurrent/thisLR;
state.layers{l}.momentum{j} = opts.momentum * state.layers{l}.momentum{j} ...
- thisDecay * net.layers{l}.weights{j} ...
- (1 / batchSize) * gradientClipping(res(l).dzdw{j},theta) ;
net.layers{l}.weights{j} = net.layers{l}.weights{j} + ...
thisLR * state.layers{l}.momentum{j} ;
else
state.layers{l}.momentum{j} = opts.momentum * state.layers{l}.momentum{j} ...
- thisDecay * net.layers{l}.weights{j} ...
- (1 / batchSize) * res(l).dzdw{j} ;
net.layers{l}.weights{j} = net.layers{l}.weights{j} + ...
thisLR * state.layers{l}.momentum{j} ;
end
end
end
end
case 'Adam' %%% solver: Adam
for l=numel(net.layers):-1:1
for j=1:numel(res(l).dzdw)
if j == 3 && strcmp(net.layers{l}.type, 'bnorm')
%%% special case for learning bnorm moments
thisLR = net.layers{l}.learningRate(j) - opts.bnormLearningRate;
net.layers{l}.weights{j} = ...
(1 - thisLR) * net.layers{l}.weights{j} + ...
(thisLR/batchSize) * res(l).dzdw{j} ;
else
thisLR = state.learningRate * net.layers{l}.learningRate(j);
state.layers{l}.t{j} = state.layers{l}.t{j} + 1;
t = state.layers{l}.t{j};
alpha = thisLR;
lr = alpha * sqrt(1 - opts.beta2^t) / (1 - opts.beta1^t);
state.layers{l}.m{j} = state.layers{l}.m{j} + (1 - opts.beta1) .* (res(l).dzdw{j} - state.layers{l}.m{j});
state.layers{l}.v{j} = state.layers{l}.v{j} + (1 - opts.beta2) .* (res(l).dzdw{j} .* res(l).dzdw{j} - state.layers{l}.v{j});
if opts.gradientClipping
theta = opts.thetaCurrent/lr;
net.layers{l}.weights{j} = net.layers{l}.weights{j} - lr * gradientClipping(state.layers{l}.m{j} ./ (sqrt(state.layers{l}.v{j}) + opts.epsilon),theta);
else
net.layers{l}.weights{j} = net.layers{l}.weights{j} - lr * state.layers{l}.m{j} ./ (sqrt(state.layers{l}.v{j}) + opts.epsilon);
end
end
end
end
end
%%%-------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir,modelName)
%%%-------------------------------------------------------------------------
list = dir(fullfile(modelDir, [modelName,'-epoch-*.mat'])) ;
tokens = regexp({list.name}, [modelName,'-epoch-([\d]+).mat'], 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
%%%-------------------------------------------------------------------------
function A = gradientClipping(A, theta)
%%%-------------------------------------------------------------------------
A(A>theta) = theta;
A(A<-theta) = -theta;
%%%-------------------------------------------------------------------------
function fn = getBatch
%%%-------------------------------------------------------------------------
fn = @(x,y) getSimpleNNBatch(x,y);
%%%-------------------------------------------------------------------------
function [inputs,labels] = getSimpleNNBatch(imdb, batch)
%%%-------------------------------------------------------------------------
inputs = imdb.inputs(:,:,:,batch);
labels = imdb.labels(:,:,:,batch);
|
github | cszn/DnCNN-master | Cal_PSNRSSIM.m | .m | DnCNN-master/TrainingCodes/DnCNN_TrainingCodes_v1.0/data/utilities/Cal_PSNRSSIM.m | 6,471 | utf_8 | 1689b76bfd626a066df745e53cf59f19 | function [psnr_cur, ssim_cur] = Cal_PSNRSSIM(A,B,row,col)
[n,m,ch]=size(B);
A = A(row+1:n-row,col+1:m-col,:);
B = B(row+1:n-row,col+1:m-col,:);
A=double(A); % Ground-truth
B=double(B); %
e=A(:)-B(:);
mse=mean(e.^2);
psnr_cur=10*log10(255^2/mse);
if ch==1
[ssim_cur, ~] = ssim_index(A, B);
else
ssim_cur = -1;
end
function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L)
%========================================================================
%SSIM Index, Version 1.0
%Copyright(c) 2003 Zhou Wang
%All Rights Reserved.
%
%The author is with Howard Hughes Medical Institute, and Laboratory
%for Computational Vision at Center for Neural Science and Courant
%Institute of Mathematical Sciences, New York University.
%
%----------------------------------------------------------------------
%Permission to use, copy, or modify this software and its documentation
%for educational and research purposes only and without fee is hereby
%granted, provided that this copyright notice and the original authors'
%names appear on all copies and supporting documentation. This program
%shall not be used, rewritten, or adapted as the basis of a commercial
%software or hardware product without first obtaining permission of the
%authors. The authors make no representations about the suitability of
%this software for any purpose. It is provided "as is" without express
%or implied warranty.
%----------------------------------------------------------------------
%
%This is an implementation of the algorithm for calculating the
%Structural SIMilarity (SSIM) index between two images. Please refer
%to the following paper:
%
%Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image
%quality assessment: From error measurement to structural similarity"
%IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004.
%
%Kindly report any suggestions or corrections to [email protected]
%
%----------------------------------------------------------------------
%
%Input : (1) img1: the first image being compared
% (2) img2: the second image being compared
% (3) K: constants in the SSIM index formula (see the above
% reference). defualt value: K = [0.01 0.03]
% (4) window: local window for statistics (see the above
% reference). default widnow is Gaussian given by
% window = fspecial('gaussian', 11, 1.5);
% (5) L: dynamic range of the images. default: L = 255
%
%Output: (1) mssim: the mean SSIM index value between 2 images.
% If one of the images being compared is regarded as
% perfect quality, then mssim can be considered as the
% quality measure of the other image.
% If img1 = img2, then mssim = 1.
% (2) ssim_map: the SSIM index map of the test image. The map
% has a smaller size than the input images. The actual size:
% size(img1) - size(window) + 1.
%
%Default Usage:
% Given 2 test images img1 and img2, whose dynamic range is 0-255
%
% [mssim ssim_map] = ssim_index(img1, img2);
%
%Advanced Usage:
% User defined parameters. For example
%
% K = [0.05 0.05];
% window = ones(8);
% L = 100;
% [mssim ssim_map] = ssim_index(img1, img2, K, window, L);
%
%See the results:
%
% mssim %Gives the mssim value
% imshow(max(0, ssim_map).^4) %Shows the SSIM index map
%
%========================================================================
if (nargin < 2 || nargin > 5)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5); %
K(1) = 0.01; % default settings
K(2) = 0.03; %
L = 255; %
end
if (nargin == 3)
if ((M < 11) || (N < 11))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5);
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 5)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
ssim_index = -Inf;
ssim_map = -Inf;
return
end
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
else
ssim_index = -Inf;
ssim_map = -Inf;
return;
end
end
C1 = (K(1)*L)^2;
C2 = (K(2)*L)^2;
window = window/sum(sum(window));
img1 = double(img1);
img2 = double(img2);
mu1 = filter2(window, img1, 'valid');
mu2 = filter2(window, img2, 'valid');
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;
if (C1 > 0 & C2 > 0)
ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
else
numerator1 = 2*mu1_mu2 + C1;
numerator2 = 2*sigma12 + C2;
denominator1 = mu1_sq + mu2_sq + C1;
denominator2 = sigma1_sq + sigma2_sq + C2;
ssim_map = ones(size(mu1));
index = (denominator1.*denominator2 > 0);
ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));
index = (denominator1 ~= 0) & (denominator2 == 0);
ssim_map(index) = numerator1(index)./denominator1(index);
end
mssim = mean2(ssim_map);
return
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_compile.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/vl_compile.m | 5,060 | utf_8 | 978f5189bb9b2a16db3368891f79aaa6 | function vl_compile(compiler)
% VL_COMPILE Compile VLFeat MEX files
% VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command
% works only under Windows and is used to re-build problematic
% binaries. The preferred method of compiling VLFeat on both UNIX
% and Windows is through the provided Makefiles.
%
% VL_COMPILE() only compiles the MEX files and assumes that the
% VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has
% already been built. This file is built by the Makefiles.
%
% By default VL_COMPILE() assumes that Visual C++ is the active
% MATLAB compiler. VL_COMPILE('lcc') assumes that the active
% compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does
% not seem to be able to compile the latest versions of VLFeat due
% to bugs in the support of 64-bit integers. Therefore it is
% recommended to use Visual C++ instead.
%
% See also: VL_NOPREFIX(), VL_HELP().
% Authors: Andrea Vedadli, Jonghyun Choi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 1, compiler = 'visualc' ; end
switch lower(compiler)
case 'visualc'
fprintf('%s: assuming that Visual C++ is the active compiler\n', mfilename) ;
useLcc = false ;
case 'lcc'
fprintf('%s: assuming that LCC is the active compiler\n', mfilename) ;
warning('LCC may fail to compile VLFeat. See help vl_compile.') ;
useLcc = true ;
otherwise
error('Unknown compiler ''%s''.', compiler)
end
vlDir = vl_root ;
toolboxDir = fullfile(vlDir, 'toolbox') ;
switch computer
case 'PCWIN'
fprintf('%s: compiling for PCWIN (32 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ;
binwDir = fullfile(vlDir, 'bin', 'win32') ;
case 'PCWIN64'
fprintf('%s: compiling for PCWIN64 (64 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ;
binwDir = fullfile(vlDir, 'bin', 'win64') ;
otherwise
error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ;
end
impLibPath = fullfile(binwDir, 'vl.lib') ;
libDir = fullfile(binwDir, 'vl.dll') ;
mkd(mexwDir) ;
% find the subdirectories of toolbox that we should process
subDirs = dir(toolboxDir) ;
subDirs = subDirs([subDirs.isdir]) ;
discard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ;
keep = cellfun('isempty', discard) ;
subDirs = subDirs(keep) ;
subDirs = {subDirs.name} ;
% Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ~exist(fullfile(binwDir, 'vl.dll'))
error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ...
fullfile(binwDir, 'vl.dll')) ;
end
tmp = dir(fullfile(binwDir, '*.dll')) ;
supportFileNames = {tmp.name} ;
for fi = 1:length(supportFileNames)
name = supportFileNames{fi} ;
cp(fullfile(binwDir, name), ...
fullfile(mexwDir, name) ) ;
end
% Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if useLcc
lccImpLibDir = fullfile(mexwDir, 'lcc') ;
lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ;
lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ;
lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ;
mkd(lccImpLibDir) ;
cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ;
cmd = ['"' lccImpExePath '"', ' -u ', '"' fullfile(lccImpLibDir, 'vl.dll') '"'] ;
fprintf('Running:\n> %s\n', cmd) ;
curPath = pwd ;
try
cd(lccImpLibDir) ;
[d,w] = system(cmd) ;
if d, error(w); end
cd(curPath) ;
catch
cd(curPath) ;
error(lasterr) ;
end
end
% Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for i = 1:length(subDirs)
thisDir = fullfile(toolboxDir, subDirs{i}) ;
fileNames = ls(fullfile(thisDir, '*.c'));
for f = 1:size(fileNames,1)
fileName = fileNames(f, :) ;
sp = strfind(fileName, ' ');
if length(sp) > 0, fileName = fileName(1:sp-1); end
filePath = fullfile(thisDir, fileName);
fprintf('MEX %s\n', filePath);
dot = strfind(fileName, '.');
mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']);
if exist(mexFile)
delete(mexFile)
end
cmd = {['-I' toolboxDir], ...
['-I' vlDir], ...
'-O', ...
'-outdir', mexwDir, ...
filePath } ;
if useLcc
cmd{end+1} = lccImpLibPath ;
else
cmd{end+1} = impLibPath ;
end
mex(cmd{:}) ;
end
end
% --------------------------------------------------------------------
function cp(src,dst)
% --------------------------------------------------------------------
if ~exist(dst,'file')
fprintf('Copying ''%s'' to ''%s''.\n', src,dst) ;
copyfile(src,dst) ;
end
% --------------------------------------------------------------------
function mkd(dst)
% --------------------------------------------------------------------
if ~exist(dst, 'dir')
fprintf('Creating directory ''%s''.', dst) ;
mkdir(dst) ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_noprefix.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/vl_noprefix.m | 1,875 | utf_8 | 97d8755f0ba139ac1304bc423d3d86d3 | function vl_noprefix
% VL_NOPREFIX Create a prefix-less version of VLFeat commands
% VL_NOPREFIX() creats prefix-less stubs for VLFeat functions
% (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs
% are included in the VLFeat binary distribution anyways. Moreover,
% on UNIX platforms, the stubs are generally constructed by the
% Makefile.
%
% See also: VL_COMPILE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
root = fileparts(which(mfilename)) ;
list = listMFilesX(root);
outDir = fullfile(root, 'noprefix') ;
if ~exist(outDir, 'dir')
mkdir(outDir) ;
end
for li = 1:length(list)
name = list(li).name(1:end-2) ; % remove .m
nname = name(4:end) ; % remove vl_
stubPath = fullfile(outDir, [nname '.m']) ;
fout = fopen(stubPath, 'w') ;
fprintf('Creating stub %s for %s\n', stubPath, nname) ;
fprintf(fout, 'function varargout = %s(varargin)\n', nname) ;
fprintf(fout, '%% %s Stub for %s\n', upper(nname), upper(name)) ;
fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\n', name) ;
fclose(fout) ;
end
end
function list = listMFilesX(root)
list = struct('name', {}, 'path', {}) ;
files = dir(root) ;
for fi = 1:length(files)
name = files(fi).name ;
if files(fi).isdir
if any(regexp(name, '^(\.|\.\.|noprefix)$'))
continue ;
else
tmp = listMFilesX(fullfile(root, name)) ;
list = [list, tmp] ;
end
end
if any(regexp(name, '^vl_(demo|test).*m$'))
continue ;
elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\.m$'))
continue ;
elseif any(regexp(name, '\.m$'))
list(end+1) = struct(...
'name', {name}, ...
'path', {fullfile(root, name)}) ;
end
end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_pegasos.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/misc/vl_pegasos.m | 2,837 | utf_8 | d5e0915c439ece94eb5597a07090b67d | % VL_PEGASOS [deprecated]
% VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_pegasos(X,Y,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
% parameters for vl_maketrainingset
setvarargin = {};
if (sum(strcmpi('HOMKERMAP',varargin)))
setvarargin{end+1} = 'HOMKERMAP';
setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1};
varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[];
varargin(find(strcmpi('HOMKERMAP',varargin),1))=[];
end
if (sum(strcmpi('KChi2',varargin)))
setvarargin{end+1} = 'KChi2';
varargin(find(strcmpi('KChi2',varargin),1))=[];
end
if (sum(strcmpi('KINTERS',varargin)))
setvarargin{end+1} = 'KINTERS';
varargin(find(strcmpi('KINTERS',varargin),1))=[];
end
if (sum(strcmpi('KL1',varargin)))
setvarargin{end+1} = 'KL1';
varargin(find(strcmpi('KL1',varargin),1))=[];
end
if (sum(strcmpi('KJS',varargin)))
setvarargin{end+1} = 'KJS';
varargin(find(strcmpi('KJS',varargin),1))=[];
end
if (sum(strcmpi('Period',varargin)))
setvarargin{end+1} = 'Period';
setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1};
varargin(find(strcmpi('Period',varargin),1)+1)=[];
varargin(find(strcmpi('Period',varargin),1))=[];
end
if (sum(strcmpi('Window',varargin)))
setvarargin{end+1} = 'Window';
setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1};
varargin(find(strcmpi('Window',varargin),1)+1)=[];
varargin(find(strcmpi('Window',varargin),1))=[];
end
if (sum(strcmpi('Gamma',varargin)))
setvarargin{end+1} = 'Gamma';
setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1};
varargin(find(strcmpi('Gamma',varargin),1)+1)=[];
varargin(find(strcmpi('Gamma',varargin),1))=[];
end
setvarargin{:}
DATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:});
DATA
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_svmpegasos.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/misc/vl_svmpegasos.m | 1,178 | utf_8 | 009c2a2b87a375d529ed1a4dbe3af59f | % VL_SVMPEGASOS [deprecated]
% VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_override.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/misc/vl_override.m | 4,654 | utf_8 | e233d2ecaeb68f56034a976060c594c5 | function config = vl_override(config,update,varargin)
% VL_OVERRIDE Override structure subset
% CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds
% of the structure UPDATE to the corresponding fields of the
% struture CONFIG.
%
% Usually CONFIG is interpreted as a list of paramters with their
% default values and UPDATE as a list of new paramete values.
%
% VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i)
% UPDATE has a field not found in CONFIG, or (ii) non-leaf values of
% CONFIG are overwritten.
%
% VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found
% in CONFIG instead of copying them.
%
% VL_OVERRIDE(..., 'CaseI') matches field names in a
% case-insensitive manner.
%
% Remark::
% Fields are copied at the deepest possible level. For instance,
% if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the
% structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with
% fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the
% structure A.B=4, then the field A.B is copied, and VL_OVERRIDE()
% returns the structure A.B=4 (specifying 'Warn' would warn about
% the fact that the substructure B.C1, B.C2 is being deleted).
%
% Remark::
% Two fields are matched if they correspond exactly. Specifically,
% two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B
% match if, and only if, (i) A and B have the same dimensions,
% (ii) IA == IB, and (iii) FA == FB.
%
% See also: VL_ARGPARSE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
warn = false ;
skip = false ;
err = false ;
casei = false ;
if length(varargin) == 1 & ~ischar(varargin{1})
% legacy
warn = 1 ;
end
if ~warn & length(varargin) > 0
for i=1:length(varargin)
switch lower(varargin{i})
case 'warn'
warn = true ;
case 'skip'
skip = true ;
case 'err'
err = true ;
case 'argparse'
argparse = true ;
case 'casei'
casei = true ;
otherwise
error(sprintf('Unknown option ''%s''.',varargin{i})) ;
end
end
end
% if CONFIG is not a struct array just copy UPDATE verbatim
if ~isstruct(config)
config = update ;
return ;
end
% if CONFIG is a struct array but UPDATE is not, no match can be
% established and we simply copy UPDATE verbatim
if ~isstruct(update)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays, but have different
% dimensions then nom atch can be established and we simply copy
% UPDATE verbatim
if numel(update) ~= numel(config)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays of the same
% dimension, we override recursively each field
for idx=1:numel(update)
fields = fieldnames(update) ;
for i = 1:length(fields)
updateFieldName = fields{i} ;
if casei
configFieldName = findFieldI(config, updateFieldName) ;
else
configFieldName = findField(config, updateFieldName) ;
end
if ~isempty(configFieldName)
config(idx).(configFieldName) = ...
vl_override(config(idx).(configFieldName), ...
update(idx).(updateFieldName)) ;
else
if warn
warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if err
error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if skip
if warn
warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
continue ;
end
config(idx).(updateFieldName) = update(idx).(updateFieldName) ;
end
end
end
% --------------------------------------------------------------------
function field = findFieldI(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmpi(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
% --------------------------------------------------------------------
function field = findField(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmp(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_quickvis.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/quickshift/vl_quickvis.m | 3,696 | utf_8 | 27f199dad4c5b9c192a5dd3abc59f9da | function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts)
% VL_QUICKVIS Create an edge image from a Quickshift segmentation.
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. RATIO controls the tradeoff
% between color consistency and spatial consistency (See VL_QUICKSEG) and
% KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG,
% VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which
% increase the density.
%
% VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at
% most MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also
% returns the DIST thresholds that were chosen.
%
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS
% specified
%
% [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS)
% also returns the MAP and GAPS from VL_QUICKSHIFT.
%
% See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin == 4
dists = maxdist;
maxdist = max(dists);
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
else
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
[Iedge dists] = mapvis(map, gaps, dists);
function [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts)
% MAPVIS Create an edge image from a Quickshift segmentation.
% IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. MAXDIST is the maximum
% distance between neighbors which increase the density.
%
% MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most
% MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST
% thresholds that were chosen.
%
% IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified
%
% See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG
if nargin == 3
dists = maxdist;
maxdist = max(dists);
else
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
% throw away min region size instead of maxdist?
ind = find(dists < maxdist);
dists = dists(ind);
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
Iedge = zeros(size(map));
for i = 1:length(dists)
s = find(gaps >= dists(i));
mapdist = map;
mapdist(s) = s;
[mapped labels] = vl_flatmap(mapdist);
fprintf('%d/%d %d regions\n', i, length(dists), length(unique(mapped)))
borders = getborders(mapped);
Iedge(borders) = dists(i);
%Iedge(borders) = Iedge(borders) + 1;
%Iedge(borders) = i;
end
%%%%%%%%% GETBORDERS
function borders = getborders(map)
dx = conv2(map, [-1 1], 'same');
dy = conv2(map, [-1 1]', 'same');
borders = find(dx ~= 0 | dy ~= 0);
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_demo_aib.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/demo/vl_demo_aib.m | 2,928 | utf_8 | 590c6db09451ea608d87bfd094662cac | function vl_demo_aib
% VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB)
D = 4 ;
K = 20 ;
randn('state',0) ;
rand('state',0) ;
X1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ;
X2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ;
X3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ;
figure(1) ; clf ; hold on ;
vl_plotframe(X1,'color','r') ;
vl_plotframe(X2,'color','g') ;
vl_plotframe(X3,'color','b') ;
axis equal ;
xlim([-4 4]);
ylim([-4 4]);
axis off ;
rectangle('position',D*[-1 -1 2 2])
vl_demo_print('aib_basic_data', .6) ;
C = 1:K*K ;
Pcx = zeros(3,K*K) ;
f1 = quantize(X1,D,K) ;
f2 = quantize(X2,D,K) ;
f3 = quantize(X3,D,K) ;
Pcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ;
Pcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ;
Pcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ;
Pcx = Pcx / sum(Pcx(:)) ;
[parents, cost] = vl_aib(Pcx) ;
cutsize = [K*K, 10, 3, 2, 1] ;
for i=1:length(cutsize)
[cut,map,short] = vl_aibcut(parents, cutsize(i)) ;
parents_cut(short > 0) = parents(short(short > 0)) ;
C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ;
figure(i+1) ; clf ;
plotquantization(D,K,C) ; hold on ;
%plottree(D,K,parents_cut) ;
axis equal ;
axis off ;
title(sprintf('%d clusters', cutsize(i))) ;
vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ;
end
% --------------------------------------------------------------------
function f = quantize(X,D,K)
% --------------------------------------------------------------------
d = 2*D / K ;
j = round((X(1,:) + D) / d) ;
i = round((X(2,:) + D) / d) ;
j = max(min(j,K),1) ;
i = max(min(i,K),1) ;
f = sub2ind([K K],i,j) ;
% --------------------------------------------------------------------
function [i,j] = plotquantization(D,K,C)
% --------------------------------------------------------------------
hold on ;
cl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ;
d = 2*D / K ;
for i=0:K-1
for j=0:K-1
patch(d*(j+[0 1 1 0])-D, ...
d*(i+[0 0 1 1])-D, ...
cl(C(j*K+i+1),:)) ;
end
end
% --------------------------------------------------------------------
function h = plottree(D,K,parents)
% --------------------------------------------------------------------
d = 2*D / K ;
C = zeros(2,2*K*K-1)+NaN ;
N = zeros(1,2*K*K-1) ;
for i=0:K-1
for j=0:K-1
C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ;
N(:,j*K+i+1) = 1 ;
end
end
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
if all(isnan(C(:,i))), continue; end
if all(isnan(C(:,p)))
C(:,p) = C(:,i) / N(i) ;
else
C(:,p) = C(:,p) + C(:,i) / N(i) ;
end
N(p) = N(p) + 1 ;
end
C(1,:) = C(1,:) ./ N ;
C(2,:) = C(2,:) ./ N ;
xt = zeros(3, 2*length(parents)-1)+NaN ;
yt = zeros(3, 2*length(parents)-1)+NaN ;
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ;
yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ;
end
h=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_demo_alldist.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/demo/vl_demo_alldist.m | 5,460 | utf_8 | 6d008a64d93445b9d7199b55d58db7eb | function vl_demo_alldist
%
numRepetitions = 3 ;
numDimensions = 1000 ;
numSamplesRange = [300] ;
settingsRange = {{'alldist2', 'double', 'l2', }, ...
{'alldist', 'double', 'l2', 'nosimd'}, ...
{'alldist', 'double', 'l2' }, ...
{'alldist2', 'single', 'l2', }, ...
{'alldist', 'single', 'l2', 'nosimd'}, ...
{'alldist', 'single', 'l2' }, ...
{'alldist2', 'double', 'l1', }, ...
{'alldist', 'double', 'l1', 'nosimd'}, ...
{'alldist', 'double', 'l1' }, ...
{'alldist2', 'single', 'l1', }, ...
{'alldist', 'single', 'l1', 'nosimd'}, ...
{'alldist', 'single', 'l1' }, ...
{'alldist2', 'double', 'chi2', }, ...
{'alldist', 'double', 'chi2', 'nosimd'}, ...
{'alldist', 'double', 'chi2' }, ...
{'alldist2', 'single', 'chi2', }, ...
{'alldist', 'single', 'chi2', 'nosimd'}, ...
{'alldist', 'single', 'chi2' }, ...
{'alldist2', 'double', 'hell', }, ...
{'alldist', 'double', 'hell', 'nosimd'}, ...
{'alldist', 'double', 'hell' }, ...
{'alldist2', 'single', 'hell', }, ...
{'alldist', 'single', 'hell', 'nosimd'}, ...
{'alldist', 'single', 'hell' }, ...
{'alldist2', 'double', 'kl2', }, ...
{'alldist', 'double', 'kl2', 'nosimd'}, ...
{'alldist', 'double', 'kl2' }, ...
{'alldist2', 'single', 'kl2', }, ...
{'alldist', 'single', 'kl2', 'nosimd'}, ...
{'alldist', 'single', 'kl2' }, ...
{'alldist2', 'double', 'kl1', }, ...
{'alldist', 'double', 'kl1', 'nosimd'}, ...
{'alldist', 'double', 'kl1' }, ...
{'alldist2', 'single', 'kl1', }, ...
{'alldist', 'single', 'kl1', 'nosimd'}, ...
{'alldist', 'single', 'kl1' }, ...
{'alldist2', 'double', 'kchi2', }, ...
{'alldist', 'double', 'kchi2', 'nosimd'}, ...
{'alldist', 'double', 'kchi2' }, ...
{'alldist2', 'single', 'kchi2', }, ...
{'alldist', 'single', 'kchi2', 'nosimd'}, ...
{'alldist', 'single', 'kchi2' }, ...
{'alldist2', 'double', 'khell', }, ...
{'alldist', 'double', 'khell', 'nosimd'}, ...
{'alldist', 'double', 'khell' }, ...
{'alldist2', 'single', 'khell', }, ...
{'alldist', 'single', 'khell', 'nosimd'}, ...
{'alldist', 'single', 'khell' }, ...
} ;
%settingsRange = settingsRange(end-5:end) ;
styles = {} ;
for marker={'x','+','.','*','o'}
for color={'r','g','b','k','y'}
styles{end+1} = {'color', char(color), 'marker', char(marker)} ;
end
end
for ni=1:length(numSamplesRange)
for ti=1:length(settingsRange)
tocs = [] ;
for ri=1:numRepetitions
rand('state',ri) ;
randn('state',ri) ;
numSamples = numSamplesRange(ni) ;
settings = settingsRange{ti} ;
[tocs(end+1), D] = run_experiment(numDimensions, ...
numSamples, ...
settings) ;
end
means(ni,ti) = mean(tocs) ;
stds(ni,ti) = std(tocs) ;
if mod(ti-1,3) == 0
D0 = D ;
else
err = max(abs(D(:)-D0(:))) ;
fprintf('err %f\n', err) ;
if err > 1, keyboard ; end
end
end
end
if 0
figure(1) ; clf ; hold on ;
numStyles = length(styles) ;
for ti=1:length(settingsRange)
si = mod(ti - 1, numStyles) + 1 ;
h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ;
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ;
end
end
for ti=1:length(settingsRange)
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
end
figure(1) ; clf ;
barh(means(end,:)) ;
set(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ;
xlabel('Time [s]') ;
function [elaps, D] = run_experiment(numDimensions, numSamples, settings)
distType = 'l2' ;
algType = 'alldist' ;
classType = 'double' ;
useSimd = true ;
for si=1:length(settings)
arg = settings{si} ;
switch arg
case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'}
distType = arg ;
case {'alldist', 'alldist2'}
algType = arg ;
case {'single', 'double'}
classType = arg ;
case 'simd'
useSimd = true ;
case 'nosimd'
useSimd = false ;
otherwise
assert(false) ;
end
end
X = rand(numDimensions, numSamples) ;
X(X < .3) = 0 ;
switch classType
case 'double'
case 'single'
X = single(X) ;
end
vl_simdctrl(double(useSimd)) ;
switch algType
case 'alldist'
tic ; D = vl_alldist(X, distType) ; elaps = toc ;
case 'alldist2'
tic ; D = vl_alldist2(X, distType) ; elaps = toc ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_demo_ikmeans.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/demo/vl_demo_ikmeans.m | 774 | utf_8 | 17ff0bb7259d390fb4f91ea937ba7de0 | function vl_demo_ikmeans()
% VL_DEMO_IKMEANS
numData = 10000 ;
dimension = 2 ;
data = uint8(255*rand(dimension,numData)) ;
numClusters = 3^3 ;
[centers, assignments] = vl_ikmeans(data, numClusters);
figure(1) ; clf ; axis off ;
plotClusters(data, centers, assignments) ;
vl_demo_print('ikmeans_2d',0.6);
[tree, assignments] = vl_hikmeans(data,3,numClusters) ;
figure(2) ; clf ; axis off ;
plotClusters(data, [], [4 2 1] * double(assignments)) ;
vl_demo_print('hikmeans_2d',0.6);
function plotClusters(data, centers, assignments)
hold on ;
cc=jet(double(max(assignments(:))));
for i=1:max(assignments(:))
plot(data(1,assignments == i),data(2,assignments == i),'.','color',cc(i,:));
end
if ~isempty(centers)
plot(centers(1,:),centers(2,:),'k.','MarkerSize',20)
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_demo_svm.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/demo/vl_demo_svm.m | 1,235 | utf_8 | 7cf6b3504e4fc2cbd10ff3fec6e331a7 | % VL_DEMO_SVM Demo: SVM: 2D linear learning
function vl_demo_svm
y=[];X=[];
% Load training data X and their labels y
load('vl_demo_svm_data.mat')
Xp = X(:,y==1);
Xn = X(:,y==-1);
figure
plot(Xn(1,:),Xn(2,:),'*r')
hold on
plot(Xp(1,:),Xp(2,:),'*b')
axis equal ;
vl_demo_print('svm_training') ;
% Parameters
lambda = 0.01 ; % Regularization parameter
maxIter = 1000 ; % Maximum number of iterations
energy = [] ;
% Diagnostic function
function diagnostics(svm)
energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ;
end
% Training the SVM
energy = [] ;
[w b info] = vl_svmtrain(X, y, lambda,...
'MaxNumIterations',maxIter,...
'DiagnosticFunction',@diagnostics,...
'DiagnosticFrequency',1)
% Visualisation
eq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)];
line = ezplot(eq, [-0.9 0.9 -0.9 0.9]);
set(line, 'Color', [0 0.8 0],'linewidth', 2);
vl_demo_print('svm_training_result') ;
figure
hold on
plot(energy(1,:),'--b') ;
plot(energy(2,:),'-.g') ;
plot(energy(3,:),'r') ;
legend('Primal objective','Dual objective','Duality gap')
xlabel('Diagnostics iteration')
ylabel('Energy')
vl_demo_print('svm_energy') ;
end |
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_demo_kdtree_sift.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/demo/vl_demo_kdtree_sift.m | 6,832 | utf_8 | e676f80ac330a351f0110533c6ebba89 | function vl_demo_kdtree_sift
% VL_DEMO_KDTREE_SIFT
% Demonstrates the use of a kd-tree forest to match SIFT
% features. If FLANN is present, this function runs a comparison
% against it.
% AUTORIGHS
rand('state',0) ;
randn('state',0);
do_median = 0 ;
do_mean = 1 ;
% try to setup flann
if ~exist('flann_search', 'file')
if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab'))
addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ;
end
end
do_flann = exist('nearest_neighbors') == 3 ;
if ~do_flann
warning('FLANN not found. Comparison disabled.') ;
end
maxNumComparisonsRange = [1 10 50 100 200 300 400] ;
numTreesRange = [1 2 5 10] ;
% get data (SIFT features)
im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ;
im1 = single(rgb2gray(im1)) ;
im2 = single(rgb2gray(im2)) ;
[f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ;
[f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ;
% add some noise to make matches unique
d1 = single(d1) + rand(size(d1)) ;
d2 = single(d2) + rand(size(d2)) ;
% match exhaustively to get the ground truth
elapsedDirect = tic ;
D = vl_alldist(d1,d2) ;
[drop, best] = min(D, [], 1) ;
elapsedDirect = toc(elapsedDirect) ;
for ti=1:length(numTreesRange)
for vi=1:length(maxNumComparisonsRange)
v = maxNumComparisonsRange(vi) ;
t = numTreesRange(ti) ;
if do_median
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'median', ...
'numtrees', t) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons',v) ;
elapsedKD_median(vi,ti) = toc ;
errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_mean
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'mean', ...
'numtrees', t) ;
%kdtree = readflann(kdtree, '/tmp/flann.txt') ;
%checkx(kdtree, d1, 1, 1) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons', v) ;
elapsedKD_mean(vi,ti) = toc ;
errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_flann
tic ;
[i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ...
'trees', t, ...
'checks', v));
ifla = i ;
elapsedKD_flann(vi,ti) = toc;
errors_flann(vi,ti) = sum(i ~= best) / length(best) ;
errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
end
end
figure(1) ; clf ;
leg = {} ;
hnd = [] ;
sty = {{'color','r'},{'color','g'},...
{'color','b'},{'color','c'},...
{'color','k'}} ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('percentage of incorrect matches (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_incorrect',.6) ;
figure(2) ; clf ;
leg = {} ;
hnd = [] ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('relative overestimation of minmium distannce (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_distortion',.6) ;
% --------------------------------------------------------------------
function checkx(kdtree, X, t, n, mib, mab)
% --------------------------------------------------------------------
if nargin <= 4
mib = -inf * ones(size(X,1),1) ;
mab = +inf * ones(size(X,1),1) ;
end
lc = kdtree.trees(t).nodes.lowerChild(n) ;
uc = kdtree.trees(t).nodes.upperChild(n) ;
if lc < 0
for i=-lc:-uc-1
di = kdtree.trees(t).dataIndex(i) ;
if any(X(:,di) > mab)
error('a') ;
end
if any(X(:,di) < mib)
error('b') ;
end
end
return
end
i = kdtree.trees(t).nodes.splitDimension(n) ;
v = kdtree.trees(t).nodes.splitThreshold(n) ;
mab_ = mab ;
mab_(i) = min(mab(i), v) ;
checkx(kdtree, X, t, lc, mib, mab_) ;
mib_ = mib ;
mib_(i) = max(mib(i), v) ;
checkx(kdtree, X, t, uc, mib_, mab) ;
% --------------------------------------------------------------------
function kdtree = readflann(kdtree, path)
% --------------------------------------------------------------------
data = textread(path)' ;
for i=1:size(data,2)
nodeIds = data(1,:) ;
ni = find(nodeIds == data(1,i)) ;
if ~isnan(data(2,i))
% internal node
li = find(nodeIds == data(4,i)) ;
ri = find(nodeIds == data(5,i)) ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ;
kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ;
kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ;
else
di = data(3,i) + 1 ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ;
end
kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_impattern.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/imop/vl_impattern.m | 6,876 | utf_8 | 1716a4d107f0186be3d11c647bc628ce | function im = vl_impattern(varargin)
% VL_IMPATTERN Generate an image from a stock pattern
% IM=VLPATTERN(NAME) returns an instance of the specified
% pattern. These stock patterns are useful for testing algoirthms.
%
% All generated patterns are returned as an image of class
% DOUBLE. Both gray-scale and colour images have range in [0,1].
%
% VL_IMPATTERN() without arguments shows a gallery of the stock
% patterns. The following patterns are supported:
%
% Wedge::
% The image of a wedge.
%
% Cone::
% The image of a cone.
%
% SmoothChecker::
% A checkerboard with Gaussian filtering on top. Use the
% option-value pair 'sigma', SIGMA to specify the standard
% deviation of the smoothing and the pair 'step', STEP to specfity
% the checker size in pixels.
%
% ThreeDotsSquare::
% A pattern with three small dots and two squares.
%
% UniformNoise::
% Random i.i.d. noise.
%
% Blobs:
% Gaussian blobs of various sizes and anisotropies.
%
% Blobs1:
% Gaussian blobs of various orientations and anisotropies.
%
% Blob:
% One Gaussian blob. Use the option-value pairs 'sigma',
% 'orientation', and 'anisotropy' to specify the respective
% parameters. 'sigma' is the scalar standard deviation of an
% isotropic blob (the image domain is the rectangle
% [-1,1]^2). 'orientation' is the clockwise rotation (as the Y
% axis points downards). 'anisotropy' (>= 1) is the ratio of the
% the largest over the smallest axis of the blob (the smallest
% axis length is set by 'sigma'). Set 'cut' to TRUE to cut half
% half of the blob.
%
% A stock image::
% Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'.
%
% All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but
% the stock images, the default size is [128,128].
% Author: Andrea Vedaldi
% Copyright (C) 2012 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin > 0
pattern=varargin{1} ;
varargin=varargin(2:end) ;
else
pattern = 'gallery' ;
end
patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ...
'blob', 'blobs', 'blobs1', ...
'box', 'roofs1', 'roofs2', 'river1', 'river2'} ;
% spooling
switch lower(pattern)
case 'wedge', im = wedge(varargin) ;
case 'cone', im = cone(varargin) ;
case 'smoothchecker', im = smoothChecker(varargin) ;
case 'threedotssquare', im = threeDotSquare(varargin) ;
case 'uniformnoise', im = uniformNoise(varargin) ;
case 'blob', im = blob(varargin) ;
case 'blobs', im = blobs(varargin) ;
case 'blobs1', im = blobs1(varargin) ;
case {'box','roofs1','roofs2','river1','river2','spots'}
im = stockImage(pattern, varargin) ;
case 'gallery'
clf ;
num = numel(patterns) ;
for p = 1:num
vl_tightsubplot(num,p,'box','outer') ;
imagesc(vl_impattern(patterns{p}),[0 1]) ;
axis image off ;
title(patterns{p}) ;
end
colormap gray ;
return ;
otherwise
error('Unknown patter ''%s''.', pattern) ;
end
if nargout == 0
clf ; imagesc(im) ; hold on ;
colormap gray ; axis image off ;
title(pattern) ;
clear im ;
end
function [u,v,opts,args] = commonOpts(args)
opts.size = [128 128] ;
[opts,args] = vl_argparse(opts, args) ;
ur = linspace(-1,1,opts.size(2)) ;
vr = linspace(-1,1,opts.size(1)) ;
[u,v] = meshgrid(ur,vr);
function im = wedge(args)
[u,v,opts,args] = commonOpts(args) ;
im = abs(u) + abs(v) > (1/4) ;
im(v < 0) = 0 ;
function im = cone(args)
[u,v,opts,args] = commonOpts(args) ;
im = sqrt(u.^2+v.^2) ;
im = im / max(im(:)) ;
function im = smoothChecker(args)
opts.size = [128 128] ;
opts.step = 16 ;
opts.sigma = 2 ;
opts = vl_argparse(opts, args) ;
[u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ;
im = xor((mod(u,opts.step*2) < opts.step),...
(mod(v,opts.step*2) < opts.step)) ;
im = double(im) ;
im = vl_imsmooth(im, opts.sigma) ;
function im = threeDotSquare(args)
[u,v,opts,args] = commonOpts(args) ;
im = ones(size(u)) ;
im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ;
im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ;
[drop,i] = min(abs(v(:,1))) ;
[drop,j1] = min(abs(u(1,:)-1/6)) ;
[drop,j2] = min(abs(u(1,:))) ;
[drop,j3] = min(abs(u(1,:)+1/6)) ;
im(i,j1) = 0 ;
im(i,j2) = 0 ;
im(i,j3) = 0 ;
function im = blobs(args)
[u,v,opts,args] = commonOpts(args) ;
im = zeros(size(u)) ;
num = 5 ;
square = 2 / num ;
sigma = square / 2 / 3 ;
scales = logspace(log10(0.5), log10(1), num) ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ;
C = inv(A'*A) ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = blob(args)
[u,v,opts,args] = commonOpts(args) ;
opts.sigma = 0.15 ;
opts.anisotropy = .5 ;
opts.orientation = 2/3 * pi ;
opts.cut = false ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
th = opts.orientation ;
R = [cos(th) -sin(th) ; sin(th) cos(th)] ;
A = opts.sigma * R * diag([opts.anisotropy 1]) ;
T = [0;0] ;
[x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ;
im = exp(-0.5 *(x.^2 + y.^2)) ;
if opts.cut
im = im .* double(x > 0) ;
end
function im = blobs1(args)
[u,v,opts,args] = commonOpts(args) ;
opts.number = 5 ;
opts.sigma = [] ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
square = 2 / opts.number ;
num = opts.number ;
if isempty(opts.sigma)
sigma = 1/6 * square ;
else
sigma = opts.sigma * square ;
end
rotations = linspace(0,pi,num+1) ;
rotations(end) = [] ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
th = rotations(i) ;
R = [cos(th) -sin(th); sin(th) cos(th)] ;
A = sigma * R * diag([1 1/skews(j)]) ;
C = inv(A*A') ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = uniformNoise(args)
opts.size = [128 128] ;
opts.seed = 1 ;
opts = vl_argparse(opts, args) ;
state = vl_twister('state') ;
vl_twister('state',opts.seed) ;
im = vl_twister(opts.size([2 1])) ;
vl_twister('state',state) ;
function im = stockImage(pattern,args)
opts.size = [] ;
opts = vl_argparse(opts, args) ;
switch pattern
case 'river1', path='river1.jpg' ;
case 'river2', path='river2.jpg' ;
case 'roofs1', path='roofs1.jpg' ;
case 'roofs2', path='roofs2.jpg' ;
case 'box', path='box.pgm' ;
case 'spots', path='spots.jpg' ;
end
im = imread(fullfile(vl_root,'data',path)) ;
im = im2double(im) ;
if ~isempty(opts.size)
im = imresize(im, opts.size) ;
im = max(im,0) ;
im = min(im,1) ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_tpsu.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/imop/vl_tpsu.m | 1,755 | utf_8 | 09f36e1a707c069b375eb2817d0e5f13 | function [U,dU,delta]=vl_tpsu(X,Y)
% VL_TPSU Compute the U matrix of a thin-plate spline transformation
% U=VL_TPSU(X,Y) returns the matrix
%
% [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ]
% [ ]
% [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ]
%
% where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is
% the opposite -r^2 log(r^2) of the radial basis function of the
% thin plate spline specified by X and Y.
%
% [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with
% respect to the parameters Y. The derivatives are arranged in a
% Mx2xN array, one layer per column of U.
%
% See also: VL_TPS(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if exist('tpsumx')
U = tpsumx(X,Y) ;
else
M=size(X,2) ;
N=size(Y,2) ;
% Faster than repmat, but still fairly slow
r2 = ...
(X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ...
(X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ;
U = - rb(r2) ;
end
if nargout > 1
M=size(X,2) ;
N=size(Y,2) ;
dx = X( ones(N,1), :)' - Y( ones(1,M), :) ;
dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ;
r2 = (dx.^2 + dy.^2) ;
r = sqrt(r2) ;
coeff = drb(r)./(r+eps) ;
dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ;
end
% The radial basis function
function y = rb(r2)
y = zeros(size(r2)) ;
sel = find(r2 ~= 0) ;
y(sel) = - r2(sel) .* log(r2(sel)) ;
% The derivative of the radial basis function
function y = drb(r)
y = zeros(size(r)) ;
sel = find(r ~= 0) ;
y(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_xyz2lab.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/imop/vl_xyz2lab.m | 1,570 | utf_8 | 09f95a6f9ae19c22486ec1157357f0e3 | function J=vl_xyz2lab(I,il)
% VL_XYZ2LAB Convert XYZ color space to LAB
% J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format.
%
% VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55,
% D65, D75, D93. The default illuminatn is E.
%
% See also: VL_XYZ2LUV(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 2
il='E' ;
end
switch lower(il)
case 'a'
xw = 0.4476 ;
yw = 0.4074 ;
case 'b'
xw = 0.3324 ;
yw = 0.3474 ;
case 'c'
xw = 0.3101 ;
yw = 0.3162 ;
case 'e'
xw = 1/3 ;
yw = 1/3 ;
case 'd50'
xw = 0.3457 ;
yw = 0.3585 ;
case 'd55'
xw = 0.3324 ;
yw = 0.3474 ;
case 'd65'
xw = 0.312713 ;
yw = 0.329016 ;
case 'd75'
xw = 0.299 ;
yw = 0.3149 ;
case 'd93'
xw = 0.2848 ;
yw = 0.2932 ;
end
J=zeros(size(I)) ;
% Reference white
Yw = 1.0 ;
Xw = xw/yw ;
Zw = (1-xw-yw)/yw * Yw ;
% XYZ components
X = I(:,:,1) ;
Y = I(:,:,2) ;
Z = I(:,:,3) ;
x = X/Xw ;
y = Y/Yw ;
z = Z/Zw ;
L = 116 * f(y) - 16 ;
a = 500*(f(x) - f(y)) ;
b = 200*(f(y) - f(z)) ;
J = cat(3,L,a,b) ;
% --------------------------------------------------------------------
function b=f(a)
% --------------------------------------------------------------------
sp = find(a > 0.00856) ;
sm = find(a <= 0.00856) ;
k = 903.3 ;
b=zeros(size(a)) ;
b(sp) = a(sp).^(1/3) ;
b(sm) = (k*a(sm) + 16)/116 ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_gmm.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_gmm.m | 1,332 | utf_8 | 76782cae6c98781c6c38d4cbf5549d94 | function results = vl_test_gmm(varargin)
% VL_TEST_GMM
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
end
function s = setup()
randn('state',0) ;
s.X = randn(128, 1000) ;
end
function test_multithreading(s)
dataTypes = {'single','double'} ;
for dataType = dataTypes
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
vl_threads(0) ;
[means, covariances, priors, ll, posteriors] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_twister('state',0) ;
vl_threads(1) ;
[means_, covariances_, priors_, ll_, posteriors_] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_assert_almost_equal(means, means_, 1e-2) ;
vl_assert_almost_equal(covariances, covariances_, 1e-2) ;
vl_assert_almost_equal(priors, priors_, 1e-2) ;
vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ;
vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ;
end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_twister.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_twister.m | 1,251 | utf_8 | 2bfb5a30cbd6df6ac80c66b73f8646da | function results = vl_test_twister(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_illegal_args()
vl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ;
function test_seed_by_scalar()
rand('twister',1) ; a = rand ;
vl_twister('state',1) ; b = vl_twister ;
vl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ;
function test_get_set_state()
rand('twister',1) ; a = rand('twister') ;
vl_twister('state',1) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'read state') ;
a(1) = a(1) + 1 ;
vl_twister('state',a) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'set state') ;
function test_multi_dimensions()
b = rand('twister') ;
rand('twister',b) ;
vl_twister('state',b) ;
a=rand([1 2 3 4 5]) ;
b=vl_twister([1 2 3 4 5]) ;
vl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ;
function test_multi_multi_args()
rand('twister',1) ; a=rand(1, 2, 3, 4, 5) ;
vl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ;
vl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ;
function test_square()
rand('twister',1) ; a=rand(10) ;
vl_twister('state',1) ; b=vl_twister(10) ;
vl_assert_equal(a,b,'VL_TWISTER(N)') ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_kdtree.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_kdtree.m | 2,449 | utf_8 | 9d7ad2b435a88c22084b38e5eb5f9eb9 | function results = vl_test_kdtree(varargin)
% VL_TEST_KDTREE
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = single(randn(10, 1000)) ;
s.Q = single(randn(10, 10)) ;
function test_nearest(s)
for tmethod = {'median', 'mean'}
for type = {@single, @double}
conv = type{1} ;
tmethod = char(tmethod) ;
X = conv(s.X) ;
Q = conv(s.Q) ;
tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ;
[nn, d2] = vl_kdtreequery(tree, X, Q) ;
D2 = vl_alldist2(X, Q, 'l2') ;
[d2_, nn_] = min(D2) ;
vl_assert_equal(...
nn,uint32(nn_),...
'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ;
vl_assert_almost_equal(...
d2,d2_,...
'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ;
end
end
function test_nearests(s)
numNeighbors = 7 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
vl_assert_equal(nn,uint32(nn_)) ;
vl_assert_almost_equal(d2,d2_) ;
function test_ann(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 50 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
function test_ann_forest(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 25 ;
numTrees = 5 ;
tree = vl_kdtreebuild(s.X, 'numTrees', 5) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_imwbackward.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_imwbackward.m | 514 | utf_8 | 33baa0784c8f6f785a2951d7f1b49199 | function results = vl_test_imwbackward(varargin)
% VL_TEST_IMWBACKWARD
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
function test_identity(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ;
function test_invalid_args(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_alphanum.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_alphanum.m | 1,624 | utf_8 | 2da2b768c2d0f86d699b8f31614aa424 | function results = vl_test_alphanum(varargin)
% VL_TEST_ALPHANUM
vl_test_init ;
function s = setup()
s.strings = ...
{'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ;
s.sortedStrings = ...
{'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ;
function test_basic(s)
sorted = vl_alphanum(s.strings) ;
assert(isequal(sorted,s.sortedStrings)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_printsize.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_printsize.m | 1,447 | utf_8 | 0f0b6437c648b7a2e1310900262bd765 | function results = vl_test_printsize(varargin)
% VL_TEST_PRINTSIZE
vl_test_init ;
function s = setup()
s.fig = figure(1) ;
s.usletter = [8.5, 11] ; % inches
s.a4 = [8.26772, 11.6929] ;
clf(s.fig) ; plot(1:10) ;
function teardown(s)
close(s.fig) ;
function test_basic(s)
for sigma = [1 0.5 0.2]
vl_printsize(s.fig, sigma) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ;
vl_assert_almost_equal(pos(1), 0, 1e-4) ;
vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ;
end
function test_papertype(s)
vl_printsize(s.fig, 1, 'papertype', 'a4') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ;
function test_margin(s)
m = 0.5 ;
vl_printsize(s.fig, 1, 'margin', m) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ;
vl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ;
function test_reference(s)
sigma = 1 ;
vl_printsize(s.fig, 1, 'reference', 'vertical') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ;
vl_assert_almost_equal(pos(2), 0, 1e-4) ;
vl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_cummax.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_cummax.m | 838 | utf_8 | 5e98ee1681d4823f32ecc4feaa218611 | function results = vl_test_cummax(varargin)
% VL_TEST_CUMMAX
vl_test_init ;
function test_basic()
vl_assert_almost_equal(...
vl_cummax(1), 1) ;
vl_assert_almost_equal(...
vl_cummax([1 2 3 4], 2), [1 2 3 4]) ;
function test_multidim()
a = [1 2 3 4 3 2 1] ;
b = [1 2 3 4 4 4 4] ;
for k=1:6
dims = ones(1,6) ;
dims(k) = numel(a) ;
a = reshape(a, dims) ;
b = reshape(b, dims) ;
vl_assert_almost_equal(...
vl_cummax(a, k), b) ;
end
function test_storage_classes()
types = {@double, @single, ...
@int32, @uint32, ...
@int16, @uint16, ...
@int8, @uint8} ;
if vl_matlabversion() > 71000
types = horzcat(types, {@int64, @uint64}) ;
end
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ;
end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_imintegral.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_imintegral.m | 1,429 | utf_8 | 4750f04ab0ac9fc4f55df2c8583e5498 | function results = vl_test_imintegral(varargin)
% VL_TEST_IMINTEGRAL
vl_test_init ;
function state = setup()
state.I = ones(5,6) ;
state.correct = [ 1 2 3 4 5 6 ;
2 4 6 8 10 12 ;
3 6 9 12 15 18 ;
4 8 12 16 20 24 ;
5 10 15 20 25 30 ; ] ;
function test_matlab_equivalent(s)
vl_assert_equal(slow_imintegral(s.I), s.correct) ;
function test_basic(s)
vl_assert_equal(vl_imintegral(s.I), s.correct) ;
function test_multi_dimensional(s)
vl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ...
repmat(s.correct, [1 1 3])) ;
function test_random(s)
numTests = 50 ;
for i = 1:numTests
I = rand(5) ;
vl_assert_almost_equal(vl_imintegral(s.I), ...
slow_imintegral(s.I)) ;
end
function test_datatypes(s)
vl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ;
vl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ;
vl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ;
function integral = slow_imintegral(I)
integral = zeros(size(I));
for k = 1:size(I,3)
for r = 1:size(I,1)
for c = 1:size(I,2)
integral(r,c,k) = sum(sum(I(1:r,1:c,k)));
end
end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_sift.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_sift.m | 1,318 | utf_8 | 806c61f9db9f2ebb1d649c9bfcf3dc0a | function results = vl_test_sift(varargin)
% VL_TEST_SIFT
vl_test_init ;
function s = setup()
s.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ;
[s.ubc.f, s.ubc.d] = ...
vl_ubcread(fullfile(vl_root,'data','box.sift')) ;
function test_ubc_descriptor(s)
err = [] ;
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'frames', s.ubc.f) ;
D2 = vl_alldist(f, s.ubc.f) ;
[drop, perm] = min(D2) ;
f = f(:,perm) ;
d = d(:,perm) ;
error = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ...
/ mean(sqrt(sum(single(s.ubc.d).^2))) ;
assert(error < 0.1, ...
'sift descriptor did not produce desctiptors similar to UBC ones') ;
function test_ubc_detector(s)
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'peakthresh', .01, ...
'edgethresh', 10) ;
s.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ;
f(4,:) = mod(f(4,:), 2*pi) ;
% scale the components so that 1 pixel erro in x,y,z is equal to a
% 10-th of angle.
S = diag([1 1 1 20/pi]);
D2 = vl_alldist(S * s.ubc.f, S * f) ;
[d2,perm] = sort(min(D2)) ;
error = sqrt(d2) ;
quant80 = round(.8 * size(f,2)) ;
% check for less than one pixel error at 80% quantile
assert(error(quant80) < 1, ...
'sift detector did not produce enough keypoints similar to UBC ones') ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_binsum.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_binsum.m | 1,377 | utf_8 | f07f0f29ba6afe0111c967ab0b353a9d | function results = vl_test_binsum(varargin)
% VL_TEST_BINSUM
vl_test_init ;
function test_three_args()
vl_assert_almost_equal(...
vl_binsum([0 0], 1, 2), [0 1]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, 1), [0 7]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ;
function test_four_args()
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ;
function test_3d_one()
Z = zeros(3,3,3) ;
B = 3*ones(3,1,3) ;
R = Z ; R(:,3,:) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, 17, B, 2), R) ;
function test_3d_two()
Z = zeros(3,3,3) ;
B = 3*ones(3,3,1) ;
X = zeros(3,3,1) ; X(:,:,1) = 17 ;
R = Z ; R(:,:,3) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, X, B, 3), R) ;
function test_storage_classes()
types = {@double, @single, ...
@int32, @uint32, ...
@int16, @uint16, ...
@int8, @uint8} ;
if vl_matlabversion() > 71000
types = horzcat(types, {@int64, @uint64}) ;
end
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ;
end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_lbp.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_lbp.m | 892 | utf_8 | a79c0ce0c85e25c0b1657f3a0b499538 | function results = vl_test_lbp(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_unfiorm_lbps(s)
% enumerate the 56 uniform lbps
q = 0 ;
for i=0:7
for j=1:7
I = zeros(3) ;
p = mod(s.pixels - i + 8, 8) + 1 ;
I(p <= j) = 1 ;
f = vl_lbp(single(I), 3) ;
q = q + 1 ;
vl_assert_equal(find(f), q) ;
end
end
% constant lbps
I = [1 1 1 ; 1 0 1 ; 1 1 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 57) ;
I = [1 1 1 ; 1 1 1 ; 1 1 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 57) ;
% other lbps
I = [1 0 1 ; 0 0 0 ; 1 0 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 58) ;
function test_fliplr(s)
randn('state',0) ;
I = randn(256,256,1,'single') ;
f = vl_lbp(fliplr(I), 8) ;
f_ = vl_lbpfliplr(vl_lbp(I, 8)) ;
vl_assert_almost_equal(f,f_,1e-3) ;
function s = setup()
s.pixels = [5 6 7 ;
4 NaN 0 ;
3 2 1] ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_colsubset.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_colsubset.m | 828 | utf_8 | be0c080007445b36333b863326fb0f15 | function results = vl_test_colsubset(varargin)
% VL_TEST_COLSUBSET
vl_test_init ;
function s = setup()
s.x = [5 2 3 6 4 7 1 9 8 0] ;
function test_beginning(s)
vl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ;
vl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ;
function test_ending(s)
vl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ;
vl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ;
function test_largest(s)
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ;
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ;
function test_smallest(s)
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ;
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ;
function test_random(s)
assert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_alldist.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_alldist.m | 2,373 | utf_8 | 9ea1a36c97fe715dfa2b8693876808ff | function results = vl_test_alldist(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js', ...
'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y), ...
@(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ;
types = {'single', 'double'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
vl_assert_almost_equal(...
vl_alldist(X,Y,dists{d}), ...
makedist(distsEquiv{d},X,Y), ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist(X,X,ker) ;
kyy = vl_alldist(Y,Y,ker) ;
kxy = vl_alldist(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_ihashsum.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_ihashsum.m | 581 | utf_8 | edc283062469af62056b0782b171f5fc | function results = vl_test_ihashsum(varargin)
% VL_TEST_IHASHSUM
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(round(16*rand(2,100))) ;
sel = find(all(s.data==0)) ;
s.data(1,sel)=1 ;
function test_hash(s)
D = size(s.data,1) ;
K = 5 ;
h = zeros(1,K,'uint32') ;
id = zeros(D,K,'uint8');
next = zeros(1,K,'uint32') ;
[h,id,next] = vl_ihashsum(h,id,next,K,s.data) ;
sel = vl_ihashfind(id,next,K,s.data) ;
count = double(h(sel)) ;
[drop,i,j] = unique(s.data','rows') ;
for k=1:size(s.data,2)
count_(k) = sum(j == j(k)) ;
end
vl_assert_equal(count,count_) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_grad.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_grad.m | 434 | utf_8 | 4d03eb33a6a4f68659f868da95930ffb | function results = vl_test_grad(varargin)
% VL_TEST_GRAD
vl_test_init ;
function s = setup()
s.I = rand(150,253) ;
s.I_small = rand(2,2) ;
function test_equiv(s)
vl_assert_equal(gradient(s.I), vl_grad(s.I)) ;
function test_equiv_small(s)
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
function test_equiv_forward(s)
Ix = diff(s.I,2,1) ;
Iy = diff(s.I,2,1) ;
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_whistc.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_whistc.m | 1,384 | utf_8 | 81c446d35c82957659840ab2a579ec2c | function results = vl_test_whistc(varargin)
% VL_TEST_WHISTC
vl_test_init ;
function test_acc()
x = ones(1, 10) ;
e = 1 ;
o = 1:10 ;
vl_assert_equal(vl_whistc(x, o, e), 55) ;
function test_basic()
x = 1:10 ;
e = 1:10 ;
o = ones(1, 10) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
x = linspace(-1,11,100) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
function test_multidim()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_nan()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
x(1:7:end) = NaN ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_no_edges()
x = rand(10, 20, 30) ;
o = ones(size(x)) ;
vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ;
vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ;
vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ;
vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ;
vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_roc.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_roc.m | 1,019 | utf_8 | 9b2ae71c9dc3eda0fc54c65d55054d0c | function results = vl_test_roc(varargin)
% VL_TEST_ROC
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ;
function test_perfect_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(info.eer, 0) ;
vl_assert_almost_equal(info.auc, 1) ;
function test_swap1_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ;
function test_swap1_tptn_stable(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ;
function test_swap1_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(info.eer, 1/3) ;
vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_dsift.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_dsift.m | 2,048 | utf_8 | fbbfb16d5a21936c1862d9551f657ccc | function results = vl_test_dsift(varargin)
% VL_TEST_DSIFT
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = rgb2gray(single(I)) ;
function test_fast_slow(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSize = 5 ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
[f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors', ...
'fast') ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift fast approximation not close') ;
function test_sift(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSizeRange = [1 1.2 5] ;
for wi = 1:length(windowSizeRange)
windowSize = windowSizeRange(wi) ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
numKeys = size(f, 2) ;
f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ;
[f_, d_] = vl_sift(s.I, ...
'magnif', magnif, ...
'frames', f_, ...
'firstoctave', -1, ...
'levels', 5, ...
'floatdescriptors', ...
'windowsize', windowSize) ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift and sift equivalence') ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_alldist2.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_alldist2.m | 2,284 | utf_8 | 89a787e3d83516653ae8d99c808b9d67 | function results = vl_test_alldist2(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
% TODO: test integer classes
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist2(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', ...
'kchi2', 'kl2', 'kl1', 'khell'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y)};
types = {'single', 'double', 'sparse'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
a = vl_alldist2(X,Y,dists{d}) ;
b = makedist(distsEquiv{d},X,Y) ;
vl_assert_almost_equal(a,b, ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist2(X,X,ker) ;
kyy = vl_alldist2(Y,Y,ker) ;
kxy = vl_alldist2(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist2(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_fisher.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_fisher.m | 2,097 | utf_8 | c9afd9ab635bd412cbf8be3c2d235f6b | function results = vl_test_fisher(varargin)
% VL_TEST_FISHER
vl_test_init ;
function s = setup()
randn('state',0) ;
dimension = 5 ;
numData = 21 ;
numComponents = 3 ;
s.x = randn(dimension,numData) ;
s.mu = randn(dimension,numComponents) ;
s.sigma2 = ones(dimension,numComponents) ;
s.prior = ones(1,numComponents) ;
s.prior = s.prior / sum(s.prior) ;
function test_basic(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_norm(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_sqrt(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_improved(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_fast(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior, true) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved', 'fast') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function enc = simple_fisher(x, mu, sigma2, pri, fast)
if nargin < 5, fast = false ; end
sigma = sqrt(sigma2) ;
for k = 1:size(mu,2)
delta{k} = bsxfun(@times, bsxfun(@minus, x, mu(:,k)), 1./sigma(:,k)) ;
q(k,:) = log(pri(k)) - 0.5 * sum(log(sigma2(:,k))) - 0.5 * sum(delta{k}.^2,1) ;
end
q = exp(bsxfun(@minus, q, max(q,[],1))) ;
q = bsxfun(@times, q, 1 ./ sum(q,1)) ;
n = size(x,2) ;
if fast
[~,i] = max(q) ;
q = zeros(size(q)) ;
q(sub2ind(size(q),i,1:n)) = 1 ;
end
for k = 1:size(mu,2)
u{k} = delta{k} * q(k,:)' / n / sqrt(pri(k)) ;
v{k} = (delta{k}.^2 - 1) * q(k,:)' / n / sqrt(2*pri(k)) ;
end
enc = cat(1, u{:}, v{:}) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_imsmooth.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_imsmooth.m | 1,837 | utf_8 | 718235242cad61c9804ba5e881c22f59 | function results = vl_test_imsmooth(varargin)
% VL_TEST_IMSMOOTH
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
I = max(min(vl_imdown(I),1),0) ;
s.I = single(I) ;
function test_pad_by_continuity(s)
% Convolving a constant signal padded with continuity does not change
% the signal.
I = ones(3) ;
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
J = vl_imsmooth(I, 2, ...
'kernel', ker, ...
'padding', 'continuity') ;
vl_assert_almost_equal(J, I, 1e-4, ...
'padding by continutiy with kernel = %s', ker) ;
end
function test_kernels(s)
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
for type = {@single, @double}
for simd = [0 1]
for sigma = [1 2 7]
for step = [1 2 3]
vl_simdctrl(simd) ;
conv = type{1} ;
g = equivalent_kernel(ker, sigma) ;
J = vl_imsmooth(conv(s.I), sigma, ...
'kernel', ker, ...
'padding', 'zero', ...
'subsample', step) ;
J_ = conv(convolve(s.I, g, step)) ;
vl_assert_almost_equal(J, J_, 1e-4, ...
'kernel=%s sigma=%f step=%d simd=%d', ...
ker, sigma, step, simd) ;
end
end
end
end
end
function g = equivalent_kernel(ker, sigma)
switch ker
case 'gaussian'
W = ceil(4*sigma) ;
g = exp(-.5*((-W:W)/(sigma+eps)).^2) ;
case 'triangular'
W = max(round(sigma),1) ;
g = W - abs(-W+1:W-1) ;
end
g = g / sum(g) ;
function I = convolve(I, g, step)
if strcmp(class(I),'single')
g = single(g) ;
else
g = double(g) ;
end
for k=1:size(I,3)
I(:,:,k) = conv2(g,g,I(:,:,k),'same');
end
I = I(1:step:end,1:step:end,:) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_svmtrain.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_svmtrain.m | 4,277 | utf_8 | 071b7c66191a22e8236fda16752b27aa | function results = vl_test_svmtrain(varargin)
% VL_TEST_SVMTRAIN
vl_test_init ;
end
function s = setup()
randn('state',0) ;
Np = 10 ;
Nn = 10 ;
xp = diag([1 3])*randn(2, Np) ;
xn = diag([1 3])*randn(2, Nn) ;
xp(1,:) = xp(1,:) + 2 + 1 ;
xn(1,:) = xn(1,:) - 2 + 1 ;
s.x = [xp xn] ;
s.y = [ones(1,Np) -ones(1,Nn)] ;
s.lambda = 0.01 ;
s.biasMultiplier = 10 ;
if 0
figure(1) ; clf;
vl_plotframe(xp, 'g') ; hold on ;
vl_plotframe(xn, 'r') ;
axis equal ; grid on ;
end
% Run LibSVM as an accuate solver to compare results with. Note that
% LibSVM optimizes a slightly different cost function due to the way
% the bias is handled.
% [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ;
s.w = [1.180762951236242; 0.098366470721632] ;
s.b = -1.540018443946204 ;
s.obj = obj(s, s.w, s.b) ;
end
function test_sgd_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sgd', ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', 1/s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% there are no absolute guarantees on the objective gap, but
% the heuristic SGD uses as stopping criterion seems reasonable
% within a factor 10 at least.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-2) ;
end
end
function test_sdca_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% the gap with the accurate solver cannot be
% greater than the duality gap.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-3) ;
end
end
function test_weights(s)
for algo = {'sgd', 'sdca'}
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
numRepeats = 10 ;
pos = find(s.y > 0) ;
neg = find(s.y < 0) ;
weights = ones(1, numel(s.y)) ;
weights(pos) = numRepeats ;
% simulate weighting by repeating positives
[w b info] = vl_svmtrain(...
s.x(:, [repmat(pos,1,numRepeats) neg]), ...
s.y(:, [repmat(pos,1,numRepeats) neg]), ...
s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4) ;
% apply weigthing
[w_ b_ info_] = vl_svmtrain(...
s.x, ...
s.y, ...
s.lambda, ...
'Solver', char(algo), ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4, ...
'Weights', weights) ;
vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ;
end
end
end
function test_homkermap(s)
for solver = {'sgd', 'sdca'}
for conv = {@single,@double}
conv = conv{1} ;
dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ;
vl_twister('state',0) ;
[w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ;
x_hom = vl_homkermap(conv(s.x), 1) ;
vl_twister('state',0) ;
[w b] = vl_svmtrain(x_hom, s.y, s.lambda) ;
vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ;
end
end
end
function [w,b] = accurate_solver(X, y, lambda, biasMultiplier)
addpath opt/libsvm/matlab/
N = size(X,2) ;
model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ;
w = X(:,model.SVs) * model.sv_coef ;
b = - model.rho ;
format long ;
disp('model w:')
disp(w)
disp('bias b:')
disp(b)
end
function o = obj(s, w, b)
o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_phow.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_phow.m | 549 | utf_8 | f761a3bb218af855986263c67b2da411 | function results = vl_test_phow(varargin)
% VL_TEST_PHOPW
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = single(s.I) ;
function test_gray(s)
[f,d] = vl_phow(s.I, 'color', 'gray') ;
assert(size(d,1) == 128) ;
function test_rgb(s)
[f,d] = vl_phow(s.I, 'color', 'rgb') ;
assert(size(d,1) == 128*3) ;
function test_hsv(s)
[f,d] = vl_phow(s.I, 'color', 'hsv') ;
assert(size(d,1) == 128*3) ;
function test_opponent(s)
[f,d] = vl_phow(s.I, 'color', 'opponent') ;
assert(size(d,1) == 128*3) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_kmeans.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_kmeans.m | 3,632 | utf_8 | 0e1d6f4f8101c8982a0e743e0980c65a | function results = vl_test_kmeans(varargin)
% VL_TEST_KMEANS
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = randn(128, 100) ;
function test_basic(s)
[centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ;
[centers_, assignments_, en_] = simpleKMeans(s.X, 10) ;
assert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ;
function test_algorithms(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
[centers, assignments, en] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Lloyd', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers_, assignments_, en_] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Elkan', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers__, assignments__, en__] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'ANN', ...
'Distance', distance, ...
'NumTrees', 3, ...
'MaxNumComparisons',0) ;
vl_assert_almost_equal(centers, centers_, 1e-5) ;
vl_assert_almost_equal(assignments, assignments_, 1e-5) ;
vl_assert_almost_equal(en, en_, 1e-4) ;
vl_assert_almost_equal(centers, centers__, 1e-5) ;
vl_assert_almost_equal(assignments, assignments__, 1e-5) ;
vl_assert_almost_equal(en, en__, 1e-4) ;
vl_assert_almost_equal(centers_, centers__, 1e-5) ;
vl_assert_almost_equal(assignments_, assignments__, 1e-5) ;
vl_assert_almost_equal(en_, en__, 1e-4) ;
end
end
function test_patterns(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
data = [1 1 0 0 ;
1 0 1 0] ;
data = conversion(data) ;
[centers, assignments, en] = vl_kmeans(data, 4, ...
'NumRepetitions', 100, ...
'Distance', distance) ;
assert(isempty(setdiff(data', centers', 'rows'))) ;
end
end
function [centers, assignments, en] = simpleKMeans(X, numCenters)
[dimension, numData] = size(X) ;
centers = randn(dimension, numCenters) ;
for iter = 1:10
[dists, assignments] = min(vl_alldist(centers, X)) ;
en = sum(dists) ;
centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ;
centers = vl_binsum(centers, ...
[X ; ones(1,numData)], ...
repmat(assignments, dimension+1, 1), 2) ;
centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_hikmeans.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_hikmeans.m | 463 | utf_8 | dc3b493646e66316184e86ff4e6138ab | function results = vl_test_hikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[tree, assign] = vl_hikmeans(s.data,3,100) ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_aib.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_aib.m | 1,277 | utf_8 | 78978ae54e7ebe991d136336ba4bf9c6 | function results = vl_test_aib(varargin)
% VL_TEST_AIB
vl_test_init ;
function s = setup()
s = [] ;
function test_basic(s)
Pcx = [.3 .3 0 0
0 0 .2 .2] ;
% This results in the AIB tree
%
% 1 - \
% 5 - \
% 2 - / \
% - 7
% 3 - \ /
% 6 - /
% 4 - /
%
% coded by the map [5 5 6 6 7 1] (1 denotes the root).
[parents,cost] = vl_aib(Pcx) ;
vl_assert_equal(parents, [5 5 6 6 7 7 1]) ;
vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ;
[cut,map,short] = vl_aibcut(parents,2) ;
vl_assert_equal(cut, [5 6]) ;
vl_assert_equal(map, [1 1 2 2 1 2 0]) ;
vl_assert_equal(short, [5 5 6 6 5 6 7]) ;
function test_cluster_null(s)
Pcx = [.5 .5 0 0
0 0 0 0] ;
% This results in the AIB tree
%
% 1 - \
% 5
% 2 - /
%
% 3 x
%
% 4 x
%
% If ClusterNull is specified, the values 3 and 4
% which have zero probability are merged first
%
% 1 ----------\
% 7
% 2 ----- \ /
% 6-/
% 3 -\ /
% 5 -/
% 4 -/
parents1 = vl_aib(Pcx) ;
parents2 = vl_aib(Pcx,'ClusterNull') ;
vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ;
vl_assert_equal(parents2(3), parents2(4)) ;
function x = mi(P)
% mutual information
P1 = sum(P,1) ;
P2 = sum(P,2) ;
x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_plotbox.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_plotbox.m | 414 | utf_8 | aa06ce4932a213fb933bbede6072b029 | function results = vl_test_plotbox(varargin)
% VL_TEST_PLOTBOX
vl_test_init ;
function test_basic(s)
figure(1) ; clf ;
vl_plotbox([-1 -1 1 1]') ;
xlim([-2 2]) ;
ylim([-2 2]) ;
close(1) ;
function test_multiple(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10)) ;
close(1) ;
function test_style(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ;
close(1) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_imarray.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_imarray.m | 795 | utf_8 | c5e6a5aa8c2e63e248814f5bd89832a8 | function results = vl_test_imarray(varargin)
% VL_TEST_IMARRAY
vl_test_init ;
function test_movie_rgb(s)
A = rand(23,15,3,4) ;
B = vl_imarray(A,'movie',true) ;
function test_movie_indexed(s)
cmap = get(0,'DefaultFigureColormap') ;
A = uint8(size(cmap,1)*rand(23,15,4)) ;
A = min(A,size(cmap,1)-1) ;
B = vl_imarray(A,'movie',true) ;
function test_movie_gray_indexed(s)
A = uint8(255*rand(23,15,4)) ;
B = vl_imarray(A,'movie',true,'cmap',gray(256)) ;
for k=1:size(A,3)
vl_assert_equal(squeeze(A(:,:,k)), ...
frame2im(B(k))) ;
end
function test_basic(s)
M = 3 ;
N = 4 ;
width = 32 ;
height = 15 ;
for i=1:M
for j=1:N
A{i,j} = rand(width,height) ;
end
end
A1 = A';
A1 = cat(3,A1{:}) ;
A2 = cell2mat(A) ;
B = vl_imarray(A1, 'layout', [M N]) ;
vl_assert_equal(A2,B) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_homkermap.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_homkermap.m | 1,903 | utf_8 | c157052bf4213793a961bde1f73fb307 | function results = vl_test_homkermap(varargin)
% VL_TEST_HOMKERMAP
vl_test_init ;
function check_ker(ker, n, window, period)
args = {n, ker, 'window', window} ;
if nargin > 3
args = {args{:}, 'period', period} ;
end
x = [-1 -.5 0 .5 1] ;
y = linspace(0,2,100) ;
for conv = {@single, @double}
x = feval(conv{1}, x) ;
y = feval(conv{1}, y) ;
sx = sign(x) ;
sy = sign(y) ;
psix = vl_homkermap(x, args{:}) ;
psiy = vl_homkermap(y, args{:}) ;
k = vl_alldist(psix,psiy,'kl2') ;
k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ;
vl_assert_almost_equal(k, k_, 2e-2) ;
end
function test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ;
function test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ;
function test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ;
function test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ;
function test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ;
function test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ;
function test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ;
function test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ;
function test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ;
function test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ;
function test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ;
function test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ;
function test_gamma()
x = linspace(0,1,20) ;
for gamma = linspace(.2,2,10)
k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ;
psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ;
assert(norm(k - psix'*psix) < 1e-2) ;
end
function test_negative()
x = linspace(-1,1,20) ;
k = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ;
psix = vl_homkermap(x, 3, 'kchi2') ;
assert(norm(k - psix'*psix) < 1e-2) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_slic.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_slic.m | 200 | utf_8 | 12a6465e3ef5b4bcfd7303cd8a9229d4 | function results = vl_test_slic(varargin)
% VL_TEST_SLIC
vl_test_init ;
function s = setup()
s.im = im2single(vl_impattern('roofs1')) ;
function test_slic(s)
segmentation = vl_slic(s.im, 10, 0.1) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_ikmeans.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_ikmeans.m | 466 | utf_8 | 1ee2f647ac0035ed0d704a0cd615b040 | function results = vl_test_ikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[centers, assign] = vl_ikmeans(s.data,100) ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_mser.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_mser.m | 242 | utf_8 | 1ad33563b0c86542a2978ee94e0f4a39 | function results = vl_test_mser(varargin)
% VL_TEST_MSER
vl_test_init ;
function s = setup()
s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ;
function test_mser(s)
[regions,frames] = vl_mser(s.im) ;
mask = vl_erfill(s.im, regions(1)) ;
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_inthist.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_inthist.m | 811 | utf_8 | 459027d0c54d8f197563a02ab66ef45d | function results = vl_test_inthist(varargin)
% VL_TEST_INTHIST
vl_test_init ;
function s = setup()
rand('state',0) ;
s.labels = uint32(8*rand(123, 76, 3)) ;
function test_basic(s)
l = 10 ;
hist = vl_inthist(s.labels, 'numlabels', l) ;
hist_ = inthist_slow(s.labels, l) ;
vl_assert_equal(double(hist),hist_) ;
function test_sample(s)
rand('state',0) ;
boxes = 10 * rand(4,20) + .5 ;
boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ;
boxes = min(boxes, 10) ;
boxes = uint32(boxes) ;
inthist = vl_inthist(s.labels) ;
hist = vl_sampleinthist(inthist, boxes) ;
function hist = inthist_slow(labels, numLabels)
m = size(labels,1) ;
n = size(labels,2) ;
l = numLabels ;
b = zeros(m*n,l) ;
b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ;
b = reshape(b,m,n,l) ;
for k=1:l
hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ;
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_imdisttf.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_imdisttf.m | 1,885 | utf_8 | ae921197988abeb984cbcdf9eaf80e77 | function results = vl_test_imdisttf(varargin)
% VL_TEST_DISTTF
vl_test_init ;
function test_basic()
for conv = {@single, @double}
conv = conv{1} ;
I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ;
D = vl_imdisttf(I);
assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ;
I(2,2) = -3 ;
[D,map] = vl_imdisttf(I) ;
assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ;
assert(isequal(map, 5 * ones(3))) ;
end
function test_1x1()
assert(isequal(1, vl_imdisttf(1))) ;
function test_rand()
I = rand(13,31) ;
for t=1:4
param = [rand randn rand randn] ;
[D0,map0] = imdisttf_equiv(I,param) ;
[D,map] = vl_imdisttf(I,param) ;
vl_assert_almost_equal(D,D0,1e-10)
assert(isequal(map,map0)) ;
end
function test_param()
I = zeros(3,4) ;
I(1,1) = -1 ;
[D,map] = vl_imdisttf(I,[1 0 1 0]);
assert(isequal(-[1 0 0 0 ;
0 0 0 0 ;
0 0 0 0 ;], D)) ;
D0 = -[1 .9 .6 .1 ;
0 0 0 0 ;
0 0 0 0 ;] ;
[D,map] = vl_imdisttf(I,[.1 0 1 0]);
vl_assert_almost_equal(D,D0,1e-10);
D0 = -[1 .9 .6 .1 ;
.9 .8 .5 0 ;
.6 .5 .2 0 ;] ;
[D,map] = vl_imdisttf(I,[.1 0 .1 0]);
vl_assert_almost_equal(D,D0,1e-10);
D0 = -[.9 1 .9 .6 ;
.8 .9 .8 .5 ;
.5 .6 .5 .2 ; ] ;
[D,map] = vl_imdisttf(I,[.1 1 .1 0]);
vl_assert_almost_equal(D,D0,1e-10);
function test_special()
I = rand(13,31) -.5 ;
D = vl_imdisttf(I, [0 0 1e5 0]) ;
vl_assert_almost_equal(D(:,1),min(I,[],2),1e-10);
D = vl_imdisttf(I, [1e5 0 0 0]) ;
vl_assert_almost_equal(D(1,:),min(I,[],1),1e-10);
function [D,map]=imdisttf_equiv(I,param)
D = inf + zeros(size(I)) ;
map = zeros(size(I)) ;
ur = 1:size(D,2) ;
vr = 1:size(D,1) ;
[u,v] = meshgrid(ur,vr) ;
for v_=vr
for u_=ur
E = I(v_,u_) + ...
param(1) * (u - u_ - param(2)).^2 + ...
param(3) * (v - v_ - param(4)).^2 ;
map(E < D) = sub2ind(size(I),v_,u_) ;
D = min(D,E) ;
end
end
|
github | shenjianbing/Generalized-pooling-for-robust-object-tracking-master | vl_test_vlad.m | .m | Generalized-pooling-for-robust-object-tracking-master/dependency/vlfeat-0.9.18-bin/vlfeat-0.9.18/toolbox/xtest/vl_test_vlad.m | 1,977 | utf_8 | d3797288d6edb1d445b890db3780c8ce | function results = vl_test_vlad(varargin)
% VL_TEST_VLAD
vl_test_init ;
function s = setup()
randn('state',0) ;
s.x = randn(128,256) ;
s.mu = randn(128,16) ;
assignments = rand(16, 256) ;
s.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ;
function test_basic (s)
x = [1, 2, 3] ;
mu = [0, 0, 0] ;
assignments = eye(3) ;
phi = vl_vlad(x, mu, assignments, 'unnormalized') ;
vl_assert_equal(phi, [1 2 3]') ;
mu = [0, 1, 2] ;
phi = vl_vlad(x, mu, assignments, 'unnormalized') ;
vl_assert_equal(phi, [1 1 1]') ;
phi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ;
vl_assert_equal(phi, [2 2 2]') ;
function test_rand (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ;
vl_assert_equal(phi, phi_) ;
function test_norm (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_vlad(s.x, s.mu, s.assignments) ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_sqrt (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_individual (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = reshape(phi_, size(s.x,1), []) ;
phi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ;
phi_ = phi_(:) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_mass (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = reshape(phi_, size(s.x,1), []) ;
phi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ;
phi_ = phi_(:) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function enc = simple_vlad(x, mu, assign)
for i = 1:size(assign,1)
enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ;
end
enc = cat(1, enc{:}) ;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.