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
|
fuenwang/BiomedicalSound-master
|
xdc_apodization.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_apodization.m
| 1,388 |
utf_8
|
25117e1e732a9ce4b90082b7438415be
|
% Procedure for creating an apodization time line for an aperture
%
% Calling: xdc_apodization (Th, times, values);
%
% Parameters: Th - Pointer to the transducer aperture.
% times - Time after which the associated apodization is valid.
% values - Apodization values. Matrix with one row for each
% time value and a number of columns equal to the
% number of physical elements in the aperture. At
% least one apodization value in each row must be different
% from zero.
%
% Return: none.
%
% Version 1.01, June 19, 1998 by Joergen Arendt Jensen
% Version 1.1, May 6, 2011 by JAJ - Check of zero apodization added
function res = xdc_apodization (Th,times,values)
% Check the times vector
[m1,n]=size(times);
if (n ~= 1)
error ('Times vector must have one column');
end
[m2,n]=size(values);
% Check both arrays
if (m1 ~= m2)
error ('There must be the same number of rows for times and values');
end
% Check that there is not one column with only zeros
for i=1:m1
if (sum(abs(values(i,:)))==0)
error('There must be at least one apodization value different from zero in a column')
end
end
% Call the C-part of the program to insert apodization
Mat_field (1070,Th,times,values);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_rectangles.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_rectangles.m
| 2,000 |
utf_8
|
3c16ff913ea2c63dceb2fc0ab4a15e4a
|
% Procedure for creating an aperture consisting of rectangles
%
% Calling: Th = xdc_rectangles (rect, center, focus);
%
% Parameters:
%
% rect - Information about the rectangles. One row
% for each rectangle. The contents is:
%
% Index Variable Value
% -----------------------------------------------------------------------
% 1 no The number for the physical aperture starting from one
% 2-4 x1,y1,z1 First corner coordinate
% 5-7 x2,y2,z2 Second corner coordinate
% 8-10 x3,y3,z3 Third corner coordinate
% 11-13 x4,y4,z4 Fourth corner coordinate
% 14 apo Apodization value for this element.
% 15 width Width of the element (x direction)
% 16 heigth Height of the element (y direction)
% 17-19 c1,c2,c2 Center point of the rectangle
%
% The corner coordiantes points must
% be in a sorted order, so that they are meet in
% counter clockwise order when going from 1 to 2 to 3 to 4.
% The rectangle number given must also be in increasing order.
%
% center - The center of the physical elements. One line for
% each element starting from 1.
%
% focus - The fixed focus for this aperture.
%
% All dimensions are in meters.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, August 1, 1997 by Joergen Arendt Jensen
function Th = xdc_rectangles (rect, center, focus)
% Check that all parameters are valid
[n,m] = size(rect);
if (m~=19)
error ('Field error: Not sufficient coordinates for rectangles')
end
[n,m] = size(center);
if (m~=3)
error ('Field error: Not correct size for center points')
end
[n,m] = size(focus);
if (n~=1) | (m~=3)
error ('Field error: Not correct size for focus point')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1021, rect, center, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_lines.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_lines.m
| 1,855 |
utf_8
|
29ba579e4f1931484afb9a06b2dd7a9c
|
% Procedure for creating an aperture bounded by a set of lines
%
% Calling: Th = xdc_lines (lines, center, focus);
%
% Parameters:
%
% lines - Information about the lines. One row
% for each line. The contents is:
%
% Index Variable Value
% ------------------------------------------------------------------------------
% 1 no_phys The number for the physical element starting from one
% 2 no_mat The number for the mathematical element starting from one
% 3 slope Slope of line (NaN is infinity slope)
% 4 infinity True if slope is infinity
% 5 intersect Intersection with y-axis (slope<>NaN)
% or x-axis if slope is infinity
% 6 above Whether the active aperture is above or to
% the left (for infinite slope) of the line
%
% center - The center of the physical elements. One line for
% each physical element starting from 1.
%
% focus - The fixed focus for this aperture.
%
% All dimensions are in meters.
%
% Notice that this procedure will only work for flat element positioned
% in the x-y plane.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, August 1, 1997 by Joergen Arendt Jensen
function Th = xdc_lines (lines, center, focus)
% Check that all parameters are valid
[n,m] = size(lines);
if (m~=6)
error ('Field error: Not sufficient coordinates for lines')
end
[n,m] = size(center);
if (m~=3)
error ('Field error: Not correct size for center points')
end
[n,m] = size(focus);
if (n~=1) | (m~=3)
error ('Field error: Not correct size for focus point')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1022, lines, center, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
field_init.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/field_init.m
| 826 |
utf_8
|
90e0eb5b1deed3de2124f6a97f35b1ca
|
% Procedure for initializing the Field II program system. Must be
% the first routine that is called before using the system.
%
% Calling: field_init (suppress);
%
% Return: nothing.
%
% Input: suppress: An optional argument suppress with a value
% of zero can be given to suppress the
% display of the initial field screen.
% No ACII ouput will be given, if the argument
% is -1. Debug messages will be written if
% enable by field_debug, and all error messages
% will also be printed.
%
% Version 1.2, January 20, 1999 by Joergen Arendt Jensen
function res = field_init (suppress)
% Call the C-part of the program to initialize it
if (nargin==1)
Mat_field (5001,suppress);
else
Mat_field (5001,1);
end
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_piston.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_piston.m
| 801 |
utf_8
|
2d4e9da5ba5b915ff42817cb169f086f
|
% Procedure for creating a flat, round piston transducer
%
% Calling: Th = xdc_piston (radius, ele_size);
%
% Parameters: radius - Radius of aperture.
% ele_size - Size of elements for modeling transducer.
%
% All dimensions are in meters.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, September 3, 1996 by Joergen Arendt Jensen
function Th = xdc_piston (radius, ele_size)
% Check that all parameters are valid
if (radius<0)
error ('Field error: Negative radius of physical transducer elements')
end
if (ele_size<=0) | (ele_size>radius)
error ('Field error: Illegal size of mathematical element')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1010, radius, ele_size);
|
github
|
fuenwang/BiomedicalSound-master
|
calc_scat_multi.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/calc_scat_multi.m
| 1,386 |
utf_8
|
3609fe45f60deeb44851e90d70462686
|
% Procedure for calculating the received signal from a collection of scatterers
% and for each of the elements in the receiving aperture.
%
% Calling: [scat, start_time] = calc_scat_multi (Th1, Th2, points, amplitudes);
%
% Parameters: Th1 - Pointer to the transmit aperture.
% Th2 - Pointer to the receive aperture.
% points - Scatterers. Vector with three columns (x,y,z)
% and one row for each scatterer.
% amplitudes - Scattering amplitudes. Row vector with one
% entry for each scatterer.
%
% Return: scat - Received voltage traces. One signal for
% each physical element in the receiving
% aperture.
% start_time - The time for the first sample in scat.
%
% Version 1.0, May 21, 1999 by Joergen Arendt Jensen
function [scat, start_time] = calc_scat_multi (Th1, Th2, points, amplitudes)
% Check the point array
[m1,n]=size(points);
if (n ~= 3)
error ('Points array must have three columns');
end
[m2,n]=size(amplitudes);
if (m1 ~= m2)
error ('There must be the same number of rows for points and amplitudes arrays');
end
% Call the C-part of the program to show aperture
[scat, start_time] = Mat_field (4006,Th1,Th2,points, amplitudes);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_convex_focused_multirow.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_convex_focused_multirow.m
| 3,091 |
utf_8
|
6e7bc611cdc55a3d5ee573deaaa4331e
|
% Procedure for creating a convex, elevation focused array transducer
% with an number of rows (1.5D array)
%
% Calling: Th = xdc_convex_focused_multirow (no_elem_x, width, no_ele_y, heights, kerf_x, kerf_y,
% Rconvex, Rfocus, no_sub_x, no_sub_y, focus);
%
% Parameters: no_elem_x - Number of physical elements in x-direction.
% width - Width in x-direction of elements.
% no_elem_y - Number of physical elements in y-direction.
% heights[] - Heights of the element rows in the y-direction.
% Vector with no_elem_y values.
% kerf_x - Width in x-direction between elements.
% kerf_y - Gap in y-direction between elements.
% Rconvex - Convex radius.
% Rfocus - Radius of mechanical elevation focus.
% no_sub_x - Number of sub-divisions in x-direction of physical elements.
% no_sub_y - Number of sub-divisions in y-direction of physical elements.
% focus[] - Fixed focus for array (x,y,z). Vector with three elements.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, June 26, 1998 by Joergen Arendt Jensen
function Th = xdc_focused_multirow (no_elem_x, width, no_elem_y, heights, kerf_x, kerf_y, Rconvex, Rfocus, no_sub_x, no_sub_y, focus)
% Check that all parameters are valid
if (no_elem_x<1)
error ('Field error: Illegal number of physical transducer elements in x-direction')
end
if (width<=0)
error ('Field error: Width of elements is negativ or zero')
end
if (no_elem_y<1)
error ('Field error: Illegal number of physical transducer elements in y-direction')
end
if (min(heights)<=0)
error ('Field error: Height of elements is negativ or zero')
end
if (length(heights)~=no_elem_y)
error ('Field error: Number of heights does not equal no_elem_y')
end
if ((sum(heights)+(no_elem_y-1)*kerf_y)>2*Rfocus)
error ('Field error: Total height of elements is to large')
end
if (kerf_x<0)
error ('Field error: Kerf in x-direction is negativ')
end
if (kerf_y<0)
error ('Field error: Kerf in y-direction is negativ')
end
if (Rconvex<0)
error ('Field error: Convex radius is negative')
end
if (pi*Rconvex<=(kerf_x*(no_elem_x-1)+width*no_elem_x))
error ('Field error: Width of elements is to large compared to Rconvex')
end
if (Rfocus<=0)
error ('Field error: Radius of elevation focus is negativ or zero')
end
if (no_sub_x<1) | (no_sub_y<1)
error ('Field error: Number of mathematical elements must be 1 or more')
end
if (min(size(focus))~=1) | (max(size(focus))~=3)
error ('Field error: Focus must be a vector with three elements')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1014,no_elem_x, width, no_elem_y, heights, kerf_x, kerf_y, Rconvex, Rfocus, no_sub_x, no_sub_y, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_excitation.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_excitation.m
| 574 |
utf_8
|
bac08439495579ba8898d8f45b808c19
|
% Procedure for setting the excitation pulse of an aperture
%
% Calling: xdc_excitation (Th,pulse);
%
% Parameters: Th - Pointer to the transducer aperture.
% pulse - Excitation pulse of aperture as row vector
%
% Return: None
%
% Version 1.0, November 27, 1995 by Joergen Arendt Jensen
function res = xdc_excitation (Th, pulse)
% Test that pulse is of right dimension
[n,m]=size(pulse);
if (n ~= 1)
error ('Pulse must be a row vector');
end
% Call the C-part of the program to show aperture
Mat_field (1051,Th,pulse);
|
github
|
fuenwang/BiomedicalSound-master
|
set_sampling.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/set_sampling.m
| 443 |
utf_8
|
19a9a87e44caf059edbabc33278a0f25
|
% Set the sampling frequency the system uses.
%
% Remember that the pulses used in all apertures must
% be reset for the new sampling frequency to take effect.
%
% Calling: set_sampling (fs);
%
% Parameters: fs - The new sampling frequency.
%
% Return: nothing.
%
% Version 1.0, December 7, 1995 by Joergen Arendt Jensen
function res = set_sampling(fs)
% Call the C-part of the program to initialize it
Mat_field (5020,fs);
|
github
|
fuenwang/BiomedicalSound-master
|
calc_hp.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/calc_hp.m
| 758 |
utf_8
|
d03bb55bfe2471bfa8b0101d500593b0
|
% Procedure for calculating the emitted field.
%
% Calling: [hp, start_time] = calc_hp(Th, points);
%
% Parameters: Th - Pointer to the transmit aperture.
% points - Field points. Matrix with three columns (x,y,z)
% and one row for each field point.
%
% Return: hp - Emitted pressure field
% start_time - The time for the first sample in field.
%
% Version 1.01, May 27, 2002 by Joergen Arendt Jensen
function [hp, start_time] = calc_hp (Th, points)
% Check the point array
[m,n]=size(points);
if (n ~= 3)
error ('Points array must have three columns');
end
% Call the C-part of the program to show aperture
[hp, start_time] = Mat_field (4002,Th,points);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_line_convert.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_line_convert.m
| 547 |
utf_8
|
4414b945fe2cbc13211cdc60424674b5
|
% Procedure for converting an aperture from consisting of rectangles
% to consist of triangles
%
% Calling: xdc_line_convert (Th);
%
% Parameters: A handle Th as a pointer to this transducer aperture. The
% pointer value will be the same as for the rectangular aperture.
% The rectangles defined in the aperture will be released.
%
% Version 1.0, August 5, 1999 by Joergen Arendt Jensen
function res = xdc_line_convert (Th)
% Call the C-part of the program to convert aperture
Mat_field (1031, Th);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_show.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_show.m
| 1,111 |
utf_8
|
ed012ebd65bba199cd8df0621c755e74
|
% Procedure for showing an aperture
%
% Calling: xdc_show(Th, info_type);
%
% Parameters: Th - Pointer to the transducer aperture.
% info_type - Which information to show (text string).
% The possibilities are:
% elements - information about elements
% focus - focus time line
% apo - apodization time line
% all - all information is shown
% The argument is optional, and by default all
% information is shown.
%
% Return: ASCII output on the screen about the aperture
%
% Version 1.0, November 28, 1995 by Joergen Arendt Jensen
function res = xdc_show (Th, info_type)
% Check the type argument
if nargin < 2
info_type = 'all';
end
if strcmp(info_type, 'elements')
info =1;
elseif strcmp(info_type, 'focus')
info = 2;
elseif strcmp(info_type, 'apo')
info = 3;
else
info = 0;
end
% Call the C-part of the program to show aperture
Mat_field (1100,Th,info);
|
github
|
fuenwang/BiomedicalSound-master
|
ele_apodization.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/ele_apodization.m
| 1,152 |
utf_8
|
c6a4555ea1cc728637efcd91ab5233ba
|
% Procedure for setting the apodization of individual
% mathematical elements making up the transducer
%
% Calling: ele_apodization (Th, element_no, apo);
%
% Parameters: Th - Pointer to the transducer aperture.
% element_no - Column vector with one integer for each physical
% element to set apodization for.
% apo - Apodization values. Matrix with one row for each
% physical element and a number of columns equal to the
% number of mathematical elements in the aperture.
%
% Return: none.
%
% Version 1.0, June 29, 1998 by Joergen Arendt Jensen
function res = ele_apodization (Th, element_no, apo)
% Check the element number vector
[m1,n]=size(element_no);
if (n ~= 1)
error ('Element_no vector must have one column');
end
[m2,n]=size(apo);
% Check both arrays
if (m1 ~= m2)
error ('There must be the same number of rows for element_no vector and apo matrix');
end
% Call the C-part of the program to insert apodization
Mat_field (1080, Th, element_no, apo);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_linear_array.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_linear_array.m
| 1,611 |
utf_8
|
d27a9a60bef0ec89fadd7bf249490007
|
% Procedure for creating a linear array transducer
%
% Calling: Th = xdc_linear_array (no_elements, width, height, kerf, no_sub_x, no_sub_y, focus);
%
% Parameters: no_elements - Number of physical elements.
% width - Width in x-direction of elements.
% height - Width in y-direction of elements.
% kerf - Width in x-direction between elements.
% no_sub_x - Number of sub-divisions in x-direction of elements.
% no_sub_y - Number of sub-divisions in y-direction of elements.
% focus[] - Fixed focus for array (x,y,z). Vector with three elements.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, November 20, 1995 by Joergen Arendt Jensen
function Th = xdc_linear_array (no_elements, width, height, kerf, no_sub_x, no_sub_y, focus)
% Check that all parameters are valid
if (no_elements<1)
error ('Field error: Illegal number of physical transducer elements')
end
if (width<=0) | (height<=0)
error ('Field error: Width or height is negativ or zero')
end
if (kerf<0)
error ('Field error: Kerf is negativ')
end
if (no_sub_x<1) | (no_sub_y<1)
error ('Field error: Number of mathematical elements must 1 or more')
end
if (min(size(focus))~=1) | (max(size(focus))~=3)
error ('Field error: Focus must be a vector with three elements')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1001,no_elements, width, height, kerf, no_sub_x, no_sub_y, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
calc_h.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/calc_h.m
| 792 |
utf_8
|
7ba23939c948eef024e70681a1de5ff1
|
% Procedure for calculating the spatial impulse response
% for an aperture.
%
% Calling: [h, start_time] = calc_h(Th,points);
%
% Parameters: Th - Pointer to the transducer aperture.
% points - Field points. Vector with three columns (x,y,z)
% and one row for each field point.
%
% Return: h - Spatial impulse response in m/s.
% start_time - The time for the first sample in h.
%
% Version 1.01, October 4, 1996 by Joergen Arendt Jensen
function [h, start_time] = calc_h (Th,points)
% Check the point array
[m,n]=size(points);
if (n ~= 3)
error ('Points array must have three columns');
end
% Call the C-part of the program to show aperture
[h, start_time] = Mat_field (4001,Th,points);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_focused_multirow.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_focused_multirow.m
| 2,568 |
utf_8
|
29a55e195336462ae8b6e9faef339f63
|
% Procedure for creating a linear, elevation focused array transducer
% with an number of rows (1.5D array)
%
% Calling: Th = xdc_focused_multirow (no_elem_x, width, no_ele_y, heights, kerf_x, kerf_y,
% Rfocus, no_sub_x, no_sub_y, focus);
%
% Parameters: no_elem_x - Number of physical elements in x-direction.
% width - Width in x-direction of elements.
% no_elem_y - Number of physical elements in y-direction.
% heights - Heights of the element rows in the y-direction.
% Vector with no_elem_y values.
% kerf_x - Width in x-direction between elements.
% kerf_y - Gap in y-direction between elements.
% Rfocus - Radius of mechanical elevation focus.
% no_sub_x - Number of sub-divisions in x-direction of physical elements.
% no_sub_y - Number of sub-divisions in y-direction of physical elements.
% focus[] - Fixed focus for array (x,y,z). Vector with three elements.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, June 25, 1998 by Joergen Arendt Jensen
function Th = xdc_focused_multirow (no_elem_x, width, no_elem_y, heights, kerf_x, kerf_y, Rfocus, no_sub_x, no_sub_y, focus)
% Check that all parameters are valid
if (no_elem_x<1)
error ('Field error: Illegal number of physical transducer elements in x-direction')
end
if (width<=0)
error ('Field error: Width of elements is negativ or zero')
end
if (no_elem_y<1)
error ('Field error: Illegal number of physical transducer elements in y-direction')
end
for i=1:no_elem_y
if (heights(i)<=0)
error ('Field error: Height of elements is negativ or zero')
end
end
if (kerf_x<0)
error ('Field error: Kerf in x-direction is negativ')
end
if (kerf_y<0)
error ('Field error: Kerf in y-direction is negativ')
end
if (Rfocus<=0)
error ('Field error: Radius of elevation focus is negativ or zero')
end
if (no_sub_x<1) | (no_sub_y<1)
error ('Field error: Number of mathematical elements must 1 or more')
end
if (min(size(focus))~=1) | (max(size(focus))~=3)
error ('Field error: Focus must be a vector with three elements')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1013, no_elem_x, width, no_elem_y, heights, kerf_x, kerf_y, Rfocus, no_sub_x, no_sub_y, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_focused_array.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_focused_array.m
| 1,961 |
utf_8
|
a03c5389415f577298a129c19698db4c
|
% Procedure for creating an elevation focused linear array transducer
%
% Calling: Th = xdc_focused_array (no_elements, width, height, kerf, Rfocus,
% no_sub_x, no_sub_y, focus);
%
% Parameters: no_elements - Number of physical elements.
% width - Width in x-direction of elements.
% height - Width in y-direction of elements.
% kerf - Width in x-direction between elements.
% Rfocus - Elevation focus.
% no_sub_x - Number of sub-divisions in x-direction of elements.
% no_sub_y - Number of sub-divisions in y-direction of elements.
% focus[] - Fixed focus for array (x,y,z). Vector with three elements.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.1, March 3, 1998 by Joergen Arendt Jensen
function Th = xdc_focused_array (no_elements, width, height, kerf, Rfocus, no_sub_x, no_sub_y, focus)
% Check that all parameters are valid
if (no_elements<1)
error ('Field error: Illegal number of physical transducer elements')
end
if (width<=0) | (height<=0)
error ('Field error: Width or height is negativ or zero')
end
if (kerf<0)
error ('Field error: Kerf is negativ')
end
if (Rfocus<0)
error ('Field error: Elevation focus is negativ')
end
if (no_sub_x<1)
error ('Field error: Number of mathematical elements must 1 or more in x-direction')
end
if (no_sub_y<2)
error ('Field error: Number of mathematical elements in y-direction must 2 or more to model elevation focusing')
end
if (min(size(focus))~=1) | (max(size(focus))~=3)
error ('Field error: Focus must be a vector with three elements')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1003,no_elements, width, height, kerf, Rfocus, no_sub_x, no_sub_y, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_convex_array.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_convex_array.m
| 1,797 |
utf_8
|
07ab286d9a5610c29e85a4ba04211814
|
% Procedure for creating a convex array transducer
%
% Calling: Th = xdc_convex_array (no_elements, width, height, kerf, Rconvex,
% no_sub_x, no_sub_y, focus);
%
% Parameters: no_elements - Number of physical elements.
% width - Width in x-direction of elements.
% height - Width in y-direction of elements.
% kerf - Width in x-direction between elements.
% Rconvex - Convex radius.
% no_sub_x - Number of sub-divisions in x-direction of elements.
% no_sub_y - Number of sub-divisions in y-direction of elements.
% focus[] - Fixed focus for array (x,y,z). Vector with three elements.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.1, March 3, 1998 by Joergen Arendt Jensen
function Th = xdc_convex_array (no_elements, width, height, kerf, Rconvex, no_sub_x, no_sub_y, focus)
% Check that all parameters are valid
if (no_elements<1)
error ('Field error: Illegal number of physical transducer elements')
end
if (width<=0) | (height<=0)
error ('Field error: Width or height is negativ or zero')
end
if (kerf<0)
error ('Field error: Kerf is negativ')
end
if (Rconvex<0)
error ('Field error: Convex radius is negative')
end
if (no_sub_x<1) | (no_sub_y<1)
error ('Field error: Number of mathematical elements must 1 or more')
end
if (min(size(focus))~=1) | (max(size(focus))~=3)
error ('Field error: Focus must be a vector with three elements')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1004,no_elements, width, height, kerf, Rconvex, no_sub_x, no_sub_y, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_convert.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_convert.m
| 539 |
utf_8
|
8604fda4c1a15e278645bf2cd1753e04
|
% Procedure for converting an aperture from consisting of rectangles
% to consist of triangles
%
% Calling: xdc_convert (Th);
%
% Parameters: A handle Th as a pointer to this transducer aperture. The
% pointer value will be the same as for the rectangular aperture.
% The rectangles defined in the aperture will be released.
%
% Version 1.0, October 15, 1996 by Joergen Arendt Jensen
function res = xdc_convert (Th)
% Call the C-part of the program to convert aperture
Mat_field (1030, Th);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_impulse.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_impulse.m
| 561 |
utf_8
|
47508acfd92d9a56a768a033e6c1db17
|
% Procedure for setting the impulse response of an aperture
%
% Calling: xdc_impulse (Th,pulse);
%
% Parameters: Th - Pointer to the transducer aperture.
% pulse - Impulse response of aperture as row vector
%
% Return: None
%
% Version 1.01, May 20, 1997 by Joergen Arendt Jensen
function res = xdc_impulse (Th, pulse)
% Test that pulse is of right dimension
[n,m]=size(pulse);
if (n ~= 1)
error ('Pulse must be a row vector');
end
% Call the C-part of the program to show aperture
Mat_field (1050,Th,pulse);
|
github
|
fuenwang/BiomedicalSound-master
|
ele_delay.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/ele_delay.m
| 1,137 |
utf_8
|
4796ca443b2775bc4744303e083f022c
|
% Procedure for setting the delay of individual
% mathematical elements making up the transducer
%
% Calling: ele_delay (Th, element_no, delays);
%
% Parameters: Th - Pointer to the transducer aperture.
% element_no - Column vector with one integer for each physical
% element to set delay for.
% delays - Delay values. Matrix with one row for each
% physical element and a number of columns equal to the
% number of mathematical elements in the aperture.
%
% Return: none.
%
% Version 1.0, June 29, 1998 by Joergen Arendt Jensen
function res = ele_delay (Th, element_no, delays)
% Check the element number vector
[m1,n]=size(element_no);
if (n ~= 1)
error ('Element_no vector must have one column');
end
[m2,n]=size(delays);
% Check both arrays
if (m1 ~= m2)
error ('There must be the same number of rows for element_no vector and delays matrix');
end
% Call the C-part of the program to insert apodization
Mat_field (1081, Th, element_no, delays);
|
github
|
fuenwang/BiomedicalSound-master
|
calc_scat_all.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/calc_scat_all.m
| 2,504 |
utf_8
|
a7501310b5fc586ce5873f611312544a
|
% Procedure for calculating the received signal from a collection
% of scatterers, when transmitting with each individual element
% and receiving with each of the elements in the receiving aperture.
%
% Calling: [scat, start_time] = calc_scat_all (Th1, Th2, points, amplitudes, dec_factor);
%
% Parameters: Th1 - Pointer to the transmitting aperture.
% Th2 - Pointer to the receiving aperture.
% points - Scatterers. Vector with three columns (x,y,z)
% and one row for each scatterer.
% amplitudes - Scattering amplitudes. Row vector with one
% entry for each scatterer.
% dec_factor - Decimation factor for the output sampling rate.
% The sampling frequency is then fs/dec_factor,
% where fs is the sampling frequency set in the program.
% The factor must be an integer.
%
% Return: scat - Received voltage traces. One signal for
% each physical element in the receiving
% aperture for each element in the
% transmitting aperture. The matrix is organized with
% one received signal for each receiving element and this
% is repeated for all transmitting element, so the first
% signal is transmitting with element one and receiving with
% element one. The transmitting with element one receiving with
% element two and so forth. The it is repeated with transmitting
% element 2, etc.
% start_time - The time for the first sample in scat.
%
% Version 1.2, August 17, 2001 by Joergen Arendt Jensen
function [scat, start_time] = calc_scat_all (Th1, Th2, points, amplitudes, dec_factor)
% Check the point array
[m1,n]=size(points);
if (n ~= 3)
error ('Points array must have three columns');
end
[m2,n]=size(amplitudes);
if (m1 ~= m2)
error ('There must be the same number of rows for points and amplitudes arrays');
end
dec_factor=round(dec_factor);
if (dec_factor<1)
error ('Illegal decimation factor. Must be one or larger.');
end
% Call the C-part of the program to make the calculation
[scat, start_time] = Mat_field (4007, Th1, Th2, points, amplitudes, dec_factor);
|
github
|
fuenwang/BiomedicalSound-master
|
field_end.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/field_end.m
| 295 |
utf_8
|
97a52cdc6ae50d808867fc40cca696a4
|
% Procedure for ending the Field II program system and releasing the storage.
%
% Calling: field_end ;
%
% Return: nothing.
%
% Version 1.0, November 28, 1995 by Joergen Arendt Jensen
function res = field_end ()
% Call the C-part of the program to initialize it
Mat_field (5002);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_center_focus.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_center_focus.m
| 785 |
utf_8
|
c624b22a08dca4ff6085f3792409af80
|
% Procedure for setting the center point for the focusing.
% This point is used as a reference for calculating the
% focusing delay times and as a starting point for dynamic
% focusing.
%
% Calling: xdc_center_focus (Th, point);
%
% Parameters: Th - Pointer to the transducer aperture.
% point - Focus center point.
%
% Return: none.
%
% Version 1.0, May 20, 1997 by Joergen Arendt Jensen
function res = xdc_center_focus (Th,point)
% Check the point array
[m2,n]=size(point);
if (n ~= 3)
error ('Point array must have three columns');
end
% Check both arrays
if (m2 ~= 1)
error ('There must only be one row for the center point');
end
% Call the C-part of the program to insert focus
Mat_field (1063,Th,point);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_convex_focused_array.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_convex_focused_array.m
| 2,559 |
utf_8
|
0dd7c8488c9893e0bfccae8324bdc81d
|
% Procedure for creating a convex array transducer
%
% Calling: Th = xdc_convex_focused_array (no_elements, width, height, kerf, Rconvex, Rfocus
% no_sub_x, no_sub_y, focus);
%
% Parameters: no_elements - Number of physical elements.
% width - Width in x-direction of elements.
% height - Width in y-direction of elements.
% kerf - Width in x-direction between elements.
% Rconvex - Convex radius.
% Rfocus - Radius of elevation focus.
% no_sub_x - Number of sub-divisions in x-direction of elements.
% no_sub_y - Number of sub-divisions in y-direction of elements.
% focus[] - Fixed focus for array (x,y,z). Vector with three elements.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.01, June 26, 1998 by Joergen Arendt Jensen
function Th = xdc_convex_focused_array (no_elements, width, height, kerf, Rconvex, Rfocus, no_sub_x, no_sub_y, focus)
% Check that all parameters are valid
if (no_elements<1)
error ('Field error: Illegal number of physical transducer elements')
end
if (width<=0) | (height<=0)
error ('Field error: Width or height is negativ or zero')
end
if (kerf<0)
error ('Field error: Kerf is negativ')
end
if (height > 2*Rfocus)
error ('Field error: Illegal element height for the chosen elevation focus')
end
if ( (width*no_elements+kerf*(no_elements-1)) > (pi*Rconvex))
error ('Field error: Illegal element width and kerf for the chosen convex radius')
end
if (Rconvex<0)
error ('Field error: Convex radius is negative')
end
if (pi*Rconvex<=(kerf*(no_elements-1)+width*no_elements))
error ('Field error: Width of elements is to large compared to Rconvex')
end
if (Rfocus<0)
error ('Field error: Elevation focus radius is negative')
end
if (no_sub_x<1)
error ('Field error: Number of mathematical elements must 1 or more in x-direction')
end
if (no_sub_y<2)
error ('Field error: Number of mathematical elements in y-direction must 2 or more to model elevation focusing')
end
if (min(size(focus))~=1) | (max(size(focus))~=3)
error ('Field error: Focus must be a vector with three elements')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1005,no_elements, width, height, kerf, Rconvex, Rfocus, no_sub_x, no_sub_y, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_focus_times.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_focus_times.m
| 1,021 |
utf_8
|
61d328e14b1fbffc6e758e5186c570e8
|
% Procedure for creating a focus time line for an aperture
% The user here supplies the delay times for each element
%
% Calling: xdc_times_focus (Th, times, delays);
%
% Parameters: Th - Pointer to the transducer aperture.
% times - Time after which the associated apodization is valid.
% delays - Delay values. Matrix with one row for each
% time value and a number of columns equal to the
% number of physical elements in the aperture.
%
% Return: none.
%
% Version 1.1, March 3, 1998 by Joergen Arendt Jensen
function res = xdc_focus_times (Th,times,delays)
% Check the times vector
[m1,n]=size(times);
if (n ~= 1)
error ('Times vectors must have one columns');
end
[m2,n]=size(delays);
% Check both arrays
if (m1 ~= m2)
error ('There must be the same number of rows for times and delays');
end
% Call the C-part of the program to insert focus
Mat_field (1061,Th,times,delays);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_concave.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_concave.m
| 970 |
utf_8
|
8c824a44235f0c6a21b54ef24e5ac723
|
% Procedure for creating a concave transducer
%
% Calling: Th = xdc_concave (radius, focal_radius, ele_size);
%
% Parameters: radius - Radius of aperture.
% focal_radius - Focal radius of aperture.
% ele_size - Size of elements for modeling transducer.
%
% All dimensions are in meters.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, August 21, 1996 by Joergen Arendt Jensen
function Th = xdc_concave (radius, focal_radius, ele_size)
% Check that all parameters are valid
if (radius<0)
error ('Field error: Negative radius of physical transducer elements')
end
if (focal_radius<=0)
error ('Field error: Negativ focal radius')
end
if (ele_size<=0) | (ele_size>radius)
error ('Field error: Illegal size of mathematical element')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1011, radius, focal_radius, ele_size);
|
github
|
fuenwang/BiomedicalSound-master
|
set_field.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/set_field.m
| 2,536 |
utf_8
|
06a180d9718d2ab368f3edc7017661f1
|
% Set options for the program.
%
% Calling: set_field (option_name, value);
%
% Possible options Value
%
% use_att Whether to use attenuation (<> 0 for attenuation)
% att Frequency independent attenuation in dB/m.
% freq_att Frequency dependent attenuation in dB/[m Hz]
% around the center frequency att_f0.
% att_f0 Attenuation center frequency in Hz.
% tau_m The variable tau_m in the attenuation calculation.
%
% debug Whether to print debug information (1 = yes)
% show_times Whether to print information about the time
% taken for the calculation (yes = any positive numer).
% A number large than 2 is taken as the time in seconds
% between the printing of estimates.
% use_rectangles Whether to use rectangles (1) for the apertures
% use_triangles Whether to use triangles (1) for the apertures or rectangles (0)
% use_lines Whether to use lines (1) for the apertures or rectangles (0)
%
% accurate_time_calc Whether to use accurate time calculation for rectangular elements (1)
% or an approximative calculation
% fast_integration Whether to use fast integration (1) of the responses for bound lines
% and triangles
%
% c Set the speed of sound in m/s.
% fs Set the sampling frequency.
%
% Variables used for non-linear imaging:
%
% z Characteristic acoustic impedance of the medium in kg/[m^2 s]
% dz Step for propagating the pulse in m
% BdivA The B/A parameter
%
% Return: nothing.
%
% Example: Set the attenuation to 1.5 dB/cm, 0.5 dB/[MHz cm] around
% 3 MHz and use this:
%
% set_field ('att',1.5*100);
% set_field ('Freq_att',0.5*100/1e6);
% set_field ('att_f0',3e6);
% set_field ('use_att',1);
%
% Note that the frequency independent and frequency dependent attenuation
% should normally agree, so that Freq_att*att_f0 = att.
%
% Version 1.8, August 1, 2002 by Joergen Arendt Jensen
function res = set_field (option_name, value)
% Check the option name
if (~isstr(option_name))
error ('First argument must be an option name');
end
% Call the C-part of the program to set the option
Mat_field (5050, option_name, value);
|
github
|
fuenwang/BiomedicalSound-master
|
calc_scat.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/calc_scat.m
| 1,197 |
utf_8
|
ec67e811c62195f4335010a15391b23c
|
% Procedure for calculating the received signal from a collection of scatterers.
%
% Calling: [scat, start_time] = calc_scat(Th1, Th2, points, amplitudes);
%
% Parameters: Th1 - Pointer to the transmit aperture.
% Th2 - Pointer to the receive aperture.
% points - Scatterers. Vector with three columns (x,y,z)
% and one row for each scatterer.
% amplitudes - Scattering amplitudes. Row vector with one
% entry for each scatterer.
%
% Return: scat - Received voltage trace.
% start_time - The time for the first sample in scat.
%
% Version 1.0, November 28, 1995 by Joergen Arendt Jensen
function [scat, start_time] = calc_scat (Th1, Th2, points, amplitudes)
% Check the point array
[m1,n]=size(points);
if (n ~= 3)
error ('Points array must have three columns');
end
[m2,n]=size(amplitudes);
if (m1 ~= m2)
error ('There must be the same number of rows for points and amplitudes arrays');
end
% Call the C-part of the program to show aperture
[scat, start_time] = Mat_field (4005,Th1,Th2,points, amplitudes);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_free.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_free.m
| 347 |
utf_8
|
f38fbe69e287e3b483b560a3c499c8b9
|
% Procedure for freeing the storage occupied by an aperture
%
% Calling: xdc_free(Th);
%
% Parameters: Th - Pointer to the transducer aperture.
%
% Return: None
%
% Version 1.0, November 28, 1995 by Joergen Arendt Jensen
function res = xdc_free (Th)
% Call the C-part of the program to show aperture
Mat_field (1040,Th);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_quantization.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_quantization.m
| 803 |
utf_8
|
13b54f5af11362935130d247c9458559
|
% Procedure for setting the minimum quantization interval that
% can be used when phasing the transducer.
%
% Remember that the focus time lines must be set again for the
% quantization to take effect. This setting does not affect the
% user calculated delays.
%
% Calling: xdc_quantization (Th, min_delay);
%
% Parameters: Th - Pointer to the transducer aperture.
% min_delay - The smallest delay in seconds that can be
% used by the system. No quantization is used,
% if this delay is set to zero.
%
% Return: None.
%
% Version 1.01, July 10, 1998 by Joergen Arendt Jensen
function res = xdc_quantization (Th, min_delay)
% Call the C-part of the program to set quantization
Mat_field (1065,Th,min_delay);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_2d_array.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_2d_array.m
| 2,443 |
utf_8
|
97821d42dd3f5244d52eea314110b8e8
|
% Procedure for creating a 2d (sparse) array transducer
%
% Calling: Th = xdc_2d_array (no_ele_x, no_ele_y, width, height, kerf_x, kerf_y,
% enabled, no_sub_x, no_sub_y, focus);
%
% Parameters: no_ele_x - Number of physical elements in x-direction.
% no_ele_y - Number of physical elements in y-direction.
% width - Width in x-direction of elements.
% height - Width in y-direction of elements.
% kerf_x - Width in x-direction between elements.
% kerf_y - Width in y-direction between elements.
% enabled - Matrix of size (no_ele_x, no_ele_y) indicating
% whether the physical element is used. A 1 indicates
% an enabled element and zero that it is not.
% enable(1,1) determines the state of the
% lower left element of the transducer.
% no_sub_x - Number of sub-divisions in x-direction of elements.
% no_sub_y - Number of sub-divisions in y-direction of elements.
% focus[] - Fixed focus for array (x,y,z). Vector with three elements.
%
% Return: A handle Th as a pointer to this transducer aperture.
%
% Version 1.0, December 5, 1995 by Joergen Arendt Jensen
function Th = xdc_2d_array (no_ele_x, no_ele_y, width, height, kerf_x, kerf_y, enabled, no_sub_x, no_sub_y, focus)
% Check that all parameters are valid
if (no_ele_x<1) | (no_ele_y<1)
error ('Field error: Illegal number of physical transducer elements')
end
if (width<=0) | (height<=0)
error ('Field error: Width or height is negativ or zero')
end
if (kerf_x<0) | (kerf_y<0)
error ('Field error: Kerf is negativ')
end
[n,m]=size(enabled);
if (n ~= no_ele_x) | (m ~= no_ele_y)
error ('Field error: The enabled array does not have the correct dimension')
end
if (no_sub_x<1) | (no_sub_y<1)
error ('Field error: Number of mathematical elements must 1 or more')
end
if (min(size(focus))~=1) | (max(size(focus))~=3)
error ('Field error: Focus must be a vector with three elements')
end
% Call the C-part of the program to create aperture
Th = Mat_field (1002,no_ele_x, no_ele_y, width, height, kerf_x, kerf_y, enabled, no_sub_x, no_sub_y, focus);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_get.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_get.m
| 1,373 |
utf_8
|
16e2be486c7a1780a5b0e0989f3631eb
|
% Procedure for getting data for an aperture
%
% Calling: data = xdc_get(Th, info_type);
%
% Parameters: Th - Pointer to the transducer aperture.
% info_type - Which information to get (text string).
% The possibilities are:
% rect - information about rectangular elements
% tri - information about triangular elements
% lin - information about line bounded elements
% focus - focus time line
% apo - apodization time line
%
% Return: data - data about the aperture
%
% Example: data = xdc_get (Th,'focus');
%
% Returns the delay values for this aperture. See the manual for the
% individual values content in the user's guide.
%
% Version 1.1, November 29, 2001 by Joergen Arendt Jensen
function data = xdc_get (Th, info_type)
% Check the type argument
if nargin < 2
info_type = 'rect';
end
if strcmp(info_type, 'rect')
info = 1;
elseif strcmp(info_type, 'tri')
info = 2;
elseif strcmp(info_type, 'lin')
info = 3;
elseif strcmp(info_type, 'focus')
info = 4;
elseif strcmp(info_type, 'apo')
info = 5;
else
info = 1;
end
% Call the C-part of the program to show aperture
data = Mat_field (1101,Th,info);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_times_focus.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_times_focus.m
| 1,025 |
utf_8
|
63ceefb4f93d3dcc0ceb1adf0a0dc6dc
|
% Procedure for creating a focus time line for an aperture
% The user here supplies the delay times for each element
%
% Calling: xdc_times_focus (Th, times, delays);
%
% Parameters: Th - Pointer to the transducer aperture.
% times - Time after which the associated apodization is valid.
% delays - Delay values. Matrix with one row for each
% time value and a number of columns equal to the
% number of physical elements in the aperture.
%
% Return: none.
%
% Version 1.0, November 28, 1995 by Joergen Arendt Jensen
function res = xdc_focus_times (Th,times,delays)
% Check the times vector
[m1,n]=size(times);
if (n ~= 1)
error ('Times vectors must have one columns');
end
[m2,n]=size(delays);
% Check both arrays
if (m1 ~= m2)
error ('There must be the same number of rows for times and delays');
end
% Call the C-part of the program to insert focus
Mat_field (1061,Th,times,delays);
|
github
|
fuenwang/BiomedicalSound-master
|
xdc_baffle.m
|
.m
|
BiomedicalSound-master/hw02/code/Field2/xdc_baffle.m
| 611 |
utf_8
|
3cd630e65c95f443e69b285292f0eebf
|
% Procedure for setting the baffle condition for the aperture.
%
% Calling: xdc_baffle (Th, soft_baffle);
%
% Parameters: Th - Pointer to the transducer aperture.
% soft_baffle - Whether to use the soft-baffle condition:
% 1 - using soft baffle
% 0 - using rigid baffle (default for apertures)
%
% Return: None.
%
% Version 1.0, July 10, 1998 by Joergen Arendt Jensen
function res = xdc_baffle (Th, soft_baffle)
% Call the C-part of the program to set baffle condition
Mat_field (1066, Th, soft_baffle);
|
github
|
fuenwang/BiomedicalSound-master
|
saveFig.m
|
.m
|
BiomedicalSound-master/hw04-1/code/saveFig.m
| 225 |
utf_8
|
1e79a8c1f6d13a39941aa0d64550e925
|
%
% EE6265 Fu-En Wang 106061531 HW2 11/14/2017
%
function saveFig(fig, path)
fig.PaperPositionMode = 'auto';
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];
print(fig, path, '-dpdf')
end
|
github
|
fuenwang/BiomedicalSound-master
|
saveFig.m
|
.m
|
BiomedicalSound-master/hw03/submit/saveFig.m
| 225 |
utf_8
|
1e79a8c1f6d13a39941aa0d64550e925
|
%
% EE6265 Fu-En Wang 106061531 HW2 11/14/2017
%
function saveFig(fig, path)
fig.PaperPositionMode = 'auto';
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];
print(fig, path, '-dpdf')
end
|
github
|
fuenwang/BiomedicalSound-master
|
saveFig.m
|
.m
|
BiomedicalSound-master/hw03/code/saveFig.m
| 225 |
utf_8
|
1e79a8c1f6d13a39941aa0d64550e925
|
%
% EE6265 Fu-En Wang 106061531 HW2 11/14/2017
%
function saveFig(fig, path)
fig.PaperPositionMode = 'auto';
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];
print(fig, path, '-dpdf')
end
|
github
|
maxkferg/casting-defect-detection-master
|
wacv_demo.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/wacv_demo.m
| 7,387 |
utf_8
|
17fb9188c96b8fb70d8a3822ae2e1804
|
% [T,p] = wacv_demo(fxname,clname,clparameter)
%
% Mery, D.; Arteta, C.: Automatic Defect Recognition in X-ray Testing
% using Computer Vision. In 2017 IEEE Winter Conference on Applications of
% Computer Vision, WACV2017.
%
% Paper: http://dmery.sitios.ing.uc.cl/Prints/Conferences/International/2017-WACV.pdf
%
% (c) 2017 - Domingo Mery and Carlos Artera
%
% This code needs the following toolboxes:
% - MatConvNet > http://www.vlfeat.org
% - VLFeat > http://www.vlfeat.org
% - SPAMS > http://spams-devel.gforge.inria.fr
% - Neural Networks > http://www.mathworks.com
% - Computer Vision > http://www.mathworks.com
% - LIBSVM > http://www.csie.ntu.edu.tw/ cjlin/libsvm
% - Balu > http://dmery.ing.puc.cl/index.php/balu
%
% Original images are from GDXray
% > http://dmery.ing.puc.cl/index.php/material/gdxray/
%
% Input Parameters:
% fxname : name of the features ('clp''bsif','txh','gabor','gaborfull','int','slbp','src','alx','ggl','vgg1','vgg3','vgg4')
% 'int' - Intensity features (grayvalues)
% 'lbp' - Local Binary Patterns (59 bins)
% 'lbpri' - Rotation invariant LBP (36 bins)
% 'slbp' - Semantic LBP
% 'clp' - Crossing line profile (CLP)
% 'txh' - Haralick texture feature
% 'fft' - Discrete Fourier transform
% 'dct' - Discrete cosine transform
% 'gabor' - Gabor features
% 'gabor+' - Gabor plus features
% 'bsif' - Binarized statistical image features (BSIF)
% 'hog' - Histogram of orientated gradients
% 'surf' - Speeded up robust feature (SURF)
% 'sift' - Scale invariant feature transform (SIFT)
% 'brisk' - Binary robust invariant scalable keypoint (BRISK)
% 'alex' - AlexNet (imagenet-caffe-alex.mat)
% 'ggl' - GoogleNet (imagenet-googlenet-dag.mat)
% 'vgg1' - VGG-F (imagenet-vgg-f.mat)
% 'vgg2' - VGG-very-deep-16 (imagenet-vgg-verydeep-16.mat)
% 'vgg3' - VGG-very-deep-19 (imagenet-vgg-verydeep-19.mat)
% 'vgg4' - VGG-M-2048 (imagenet-vgg-m-2048.mat)
%
% clname : name of the classifier ('knn','libsvm','ann')
% clparameter : parameter of the classifier
%
% Output Parameters:
% info.Xtrain training features
% info.Xtest testing features
% info.dtrain training labels
% info.dtest testing labels
% info.opts parameters of the learned classifier
% info.ds prediction on the testing data
% info.T confusion matrix = [ TP FP; FN TN ]
% info.acc accuracy = (TP+TN)/(TP+FP+FN+TN)
% info.opfx parameters of the features
% info.opcl parameters of the classifier
%
% Example 1:
% info = wacv_demo('lbpri','ann',15); % LBP-ri features and an Artifical
% % Neural Network with 15 hidden layers
%
% Example 2:
% info = wacv_demo('surf','knn',5); % SURF features and an KNN classifier
% % with 5 neighbours
%
% Example 3:
% info = wacv_demo('src','src',10); % SRC features (intensity) and SRC classifier
% % with 10 atoms in the sparse representation
% % warning: more than 4 hours!
% Example 4:
% info = wacv_demo('bsif','libsvm','-t 0'); % BSIF features and
% % Linear SVM classifier
%
%
% Note: The results might be a little bit different from those presented in
% Table 3 of the paper because of some random procedures (eg, ANN initialization)
function info = wacv_demo(fxname,clname,clparameter)
fprintf('\nWACV-Experiments for Defects Detection\n');
fprintf('D. Mery and C. Arteta: Automatic Defect Recognition in X-ray Testing \nusing Computer Vision (WACV2017)\n\n');
fprintf('Loading imdb.mat ...\n\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load cropped images
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
f = 'imdb.mat';
load(f)
% The 47.520 cropped images are stored in cflaws.mat as follows
% imbd.images.label 47.520 x 1: 1 means defect, 2 is no-defect
% imbd.images.id 47.520 x 1: 1, 2, 3, ... 47520
% imbd.images.set 47.520 x 1: 1 = train, 2 = validation, 3 = test
% imbd.images.obj 47.520 x 1: series of GDXray, eg. 1 means series C00001
% > cropped images from series 1 and 2 are used for testing
% imbd.images.images 32 x 32 x 47.520: 32 x 32 cropped images
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Training, validation and testing images
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
subsampling = 1; % cropped images are not subsampled
im1 = imdb.images.data(:,:,1); % a sample
i1 = find(imdb.images.set<=2)'; % training and validation
i2 = find(imdb.images.set==3)'; % testing
i1 = i1(1:subsampling:end);
i2 = i2(1:subsampling:end);
ix_train = [imdb.images.label(i1)' i1];
ix_test = [imdb.images.label(i2)' i2];
imageMean = mean(imdb.images.data(:)) ;
clear imdb
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Definition of features and classifier
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Features = %s\n',fxname);
opfx = wacv_fxdef(fxname,im1);
opfx.imageMean = imageMean;
if ischar(clparameter)
clparst = clparameter;
else
clparst = num2str(clparameter);
end
fprintf('Classifier = %s-%s\n\n',clname,clparst);
opcl = wacv_cldef(clname,clparameter);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extraction of training features
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Extracting %s features ...\n',fxname);
[Xtrain,dtrain] = exp_fx('wacv_fx',f,opfx,ix_train,[ fxname ': training features']);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extraction of testing features
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[Xtest,dtest] = exp_fx('wacv_fx',f,opfx,ix_test,[fxname ': testing features']);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Training
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Training %s-%s classifier ...\n',clname,clparst);
opts = exp_train('wacv_classifier',Xtrain,dtrain,opcl);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Testing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Testing ...\n');
ds = exp_test('wacv_test',Xtest,opts);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Evaluation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
C = Bev_confusion(ds,dtest); % Confusion Matrix
p = Bev_performance(ds,dtest); % Accuracy
fprintf('TP = %d\n',C(1,1));
fprintf('FP = %d\n',C(1,2));
fprintf('TN = %d\n',C(2,2));
fprintf('FN = %d\n',C(2,1));
fprintf('Accuracy = %5.2f%%\n\n',p*100);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Info
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
info.Xtrain = Xtrain; % training features
info.Xtest = Xtest; % testing features
info.dtrain = dtrain; % training labels
info.dtest = dtest; % testing labels
info.opts = opts; % parameters of the learned classifier
info.ds = ds; % prediction on the testing data
info.C = C; % confusion matrix
info.acc = p; % accuracy
info.opfx = opfx; % parameters of the features
info.opcl = opcl; % parameters of the classifier
|
github
|
maxkferg/casting-defect-detection-master
|
xnet_cnn.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/xnet/xnet_cnn.m
| 7,974 |
utf_8
|
aeb905b10910c4d48dddea394f5a9aa7
|
% function [net, info] = xnet_cnn(param,epochs)
function [net, info] = xnet_cnn(var1,var2,cnnmode)
if strcmp(cnnmode,'train')==1
param = var1;
epochs = var2;
train = true;
else
info = var2;
train = false;
epochs = info.opts.train.numEpochs;
param = info.param;
end
basepath = '';
opts.dataDir = fullfile(basepath) ;
opts.modelType = 'xnet' ;
opts.useGpu = false ;
opts.networkType = 'dagnn';
% sfx = opts.modelType ;
opts.expDir = fullfile(opts.dataDir, 'epochs');
opts.numFetchThreads = 60;
opts.lite = false;
opts.batchSize = 256;
% opts.imdbPath = fullfile(opts.dataDir,'imdb.mat');
opts.imdbPath = fullfile(opts.dataDir,'../imdb.mat');
opts.train.prefetch = false;
opts.model.nChannels = 1;
opts.model.colorSpace = 'gray';
opts.train.gpus = [];
opts.train.numEpochs = epochs;
opts.train.learningRate = logspace(-2, -4, 60);
%opts.train.derOutputs = {'top1err', 1,'top5err', 1} ;
% -------------------------------------------------------------------------
% Prepare model
% -------------------------------------------------------------------------
net = xnet_init(param);
% pretrain = fullfile(basepath,'minc-2500','vgg_s_fromINetGray');
% modelPath = @(ep) fullfile(pretrain, sprintf('net-epoch-%d.mat', ep));
% epoch = 20;
% fprintf('loading pretrained model at epoch %d\n', epoch);
% load(modelPath(epoch), 'net');
% net = dagnn.DagNN.loadobj(net);
%net.meta.augmentation.transformation = 'f5';
% -------------------------------------------------------------------------
% Prepare data
% -------------------------------------------------------------------------
load(opts.imdbPath);
if exist(opts.expDir,'dir')==0
mkdir(opts.expDir) ;
end
% Set the class names in the network
net.meta.classes.name = imdb.meta.classes;
imdb.images.class = [];
imdb.meta.normalization.averageImage = [];
% Compute image statistics (mean, RGB covariances, etc.)
imageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ;
n = 'xnet_data';
if exist(imageStatsPath,'var')
load(n, 'averageImage', 'rgbMean', 'rgbCovariance') ;
else
[averageImage, rgbMean, rgbCovariance] = getImageStats(opts, net.meta, imdb) ;
save(n, 'averageImage', 'rgbMean', 'rgbCovariance') ;
end
% Set the image average (use either an image or a color)
%net.meta.normalization.averageImage = averageImage ;
net.meta.normalization.averageImage = rgbMean ;
imdb.meta.normalization.averageImage = rgbMean ;
if train
% Set data augmentation statistics
[v,d] = eig(rgbCovariance) ;
net.meta.augmentation.rgbVariance = 0.1*sqrt(d)*v' ;
clear v d ;
% -------------------------------------------------------------------------
% Train
% -------------------------------------------------------------------------
[net, info] = cnn_train_dag(net, imdb, getBatchFn(opts, net.meta), ...
'expDir', opts.expDir, ...
net.meta.trainOpts,...
opts.train);
% -------------------------------------------------------------------------
% Deploy
% -------------------------------------------------------------------------
net.removeLayer('loss');
net.removeLayer('top1err');
net.addLayer('softmax', ...
dagnn.SoftMax(), ...
{'prediction','label'}, 'preddist');
info.opts = opts;
info.param = param;
else
% -------------------------------------------------------------------------
% Test
% -------------------------------------------------------------------------
% net.move('gpu');
net = var1;
opts = info.opts;
net.mode = 'test';
useGpu = numel(opts.train.gpus) > 0;
testset = find(imdb.images.set==3);
labels = imdb.images.label(testset);
classError = zeros(numel(testset),1);
Prediction = zeros(numel(testset),1);
for b = 1:opts.batchSize:numel(testset)
batch = testset(b:min(b+opts.batchSize-1,numel(testset)));
inputs = getDagNNBatch(opts, useGpu, imdb, batch);
net.eval(inputs) ;
pred = gather(net.vars(net.getVarIndex('preddist')).value) ;
[~,predClass] = max(pred,[],3);
predClass = reshape(predClass,size(predClass,4),1);
classError(b:min(b+opts.batchSize-1,numel(testset))) = labels(b:min(b+opts.batchSize-1,numel(testset)))' ~= predClass;
Prediction(b:min(b+opts.batchSize-1,numel(testset))) = predClass;
end
info.acc = 100-nnz(classError)*100/numel(testset);
info.ds = Prediction;
info.C = Bev_confusion(Prediction,labels');
info.p = Bev_performance(Prediction,labels');
% disp(' ');
% disp('--------------------');
% disp(['Accuracy = ' num2str(info.acc) '%']);
% disp('--------------------');
% disp(' ');
end
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
useGpu = numel(opts.train.gpus) > 0 ;
bopts.numThreads = opts.numFetchThreads ;
bopts.imageSize = meta.normalization.imageSize ;
bopts.border = meta.normalization.border ;
bopts.averageImage = meta.normalization.averageImage ;
bopts.rgbVariance = meta.augmentation.rgbVariance ;
bopts.transformation = meta.augmentation.transformation ;
bopts.colorSpace = opts.model.colorSpace;
fn = @(x,y) getDagNNBatch(bopts,useGpu,x,y) ;
% -------------------------------------------------------------------------
function inputs = getDagNNBatch(opts, useGpu, imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,batch);% strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
isVal = ~isempty(batch) && imdb.images.set(batch(1)) ~= 1 ;
im = zeros(size(images,1), size(images,2), 1, size(images,3),'single');
if ~isempty(imdb.meta.normalization.averageImage)
for i = 1:size(images,3)
im(:,:,:,i) = 255*images(:,:,i) - imdb.meta.normalization.averageImage;
end
else
for i = 1:size(images,3)
im(:,:,:,i) = 255*images(:,:,i);
end
end
% if ~isVal
% % training
% im = cnn_xray_get_batch(images, opts, ...
% 'prefetch', nargout == 0) ;
% else
% % validation: disable data augmentation
% im = cnn_xray_get_batch(images, opts, ...
% 'prefetch', nargout == 0, ...
% 'transformation', 'none') ;
% end
if nargout > 0
if useGpu
im = gpuArray(im) ;
end
labels = imdb.images.label(batch) ;
inputs = {'input', im, 'label', labels} ;
end
% -------------------------------------------------------------------------
function [averageImage, rgbMean, rgbCovariance] = getImageStats(opts, meta, imdb)
% -------------------------------------------------------------------------
train = find(imdb.images.set == 1) ;
train = train(1:end);
bs = 256 ;
opts.train.colorSpace = 'rgb';
fn = getBatchFn(opts, meta) ;
avg = {}; rgbm1 = {}; rgbm2 = {};
for t=1:bs:numel(train)
batch_time = tic ;
batch = train(t:min(t+bs-1, numel(train))) ;
% fprintf('collecting image stats: batch starting with image %d ...', batch(1)) ;
temp = fn(imdb, batch) ;
temp = gather(temp{2});
z = reshape(permute(temp,[3 1 2 4]),1,[]) ;
n = size(z,2) ;
avg{end+1} = mean(temp, 4) ;
rgbm1{end+1} = sum(z,2)/n ;
rgbm2{end+1} = z*z'/n ;
batch_time = toc(batch_time) ;
% fprintf(' %.2f s (%.1f images/s)\n', batch_time, numel(batch)/ batch_time) ;
end
averageImage = mean(cat(4,avg{:}),4) ;
rgbm1 = mean(cat(2,rgbm1{:}),2) ;
rgbm2 = mean(cat(3,rgbm2{:}),3) ;
rgbMean = rgbm1 ;
rgbCovariance = rgbm2 - rgbm1*rgbm1' ;
|
github
|
maxkferg/casting-defect-detection-master
|
test_examples.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/utils/test_examples.m
| 1,591 |
utf_8
|
16831be7382a9343beff5cc3fe301e51
|
function test_examples()
%TEST_EXAMPLES Test some of the examples in the `examples/` directory
addpath examples/mnist ;
addpath examples/cifar ;
trainOpts.gpus = [] ;
trainOpts.continue = true ;
num = 1 ;
exps = {} ;
for networkType = {'dagnn', 'simplenn'}
for index = 1:4
clear ex ;
ex.trainOpts = trainOpts ;
ex.networkType = char(networkType) ;
ex.index = index ;
exps{end+1} = ex ;
end
end
if num > 1
if isempty(gcp('nocreate')),
parpool('local',num) ;
end
parfor e = 1:numel(exps)
test_one(exps{e}) ;
end
else
for e = 1:numel(exps)
test_one(exps{e}) ;
end
end
% ------------------------------------------------------------------------
function test_one(ex)
% -------------------------------------------------------------------------
suffix = ['-' ex.networkType] ;
switch ex.index
case 1
cnn_mnist(...
'expDir', ['data/test-mnist' suffix], ...
'batchNormalization', false, ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 2
cnn_mnist(...
'expDir', ['data/test-mnist-bnorm' suffix], ...
'batchNormalization', true, ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 3
cnn_cifar(...
'expDir', ['data/test-cifar-lenet' suffix], ...
'modelType', 'lenet', ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 4
cnn_cifar(...
'expDir', ['data/test-cifar-nin' suffix], ...
'modelType', 'nin', ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
end
|
github
|
maxkferg/casting-defect-detection-master
|
simplenn_caffe_compare.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/utils/simplenn_caffe_compare.m
| 5,638 |
utf_8
|
8e9862ffbf247836e6ff7579d1e6dc85
|
function diffStats = simplenn_caffe_compare( net, caffeModelBaseName, testData, varargin)
% SIMPLENN_CAFFE_COMPARE compare the simplenn network and caffe models
% SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME) Evaluates a forward
% pass of a simplenn network NET and caffe models stored in
% CAFFE_BASE_MODELNAME and numerically compares the network outputs using
% a random input data.
%
% SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME, TEST_DATA) Evaluates
% the simplenn network and Caffe model on a given data. If TEST_DATA is
% an empty array, uses a random input.
%
% RES = SIMPLENN_CAFFE_COMPARE(...) returns a structure with the
% statistics of the differences where each field of a structure RES is
% named after a blob and contains basic statistics:
% `[MIN_DIFF, MEAN_DIFF, MAX_DIFF]`
%
% This script attempts to match the NET layer names and caffe blob names
% and shows the MIN, MEAN and MAX difference between the outputs. For
% caffe model, the mean image stored with the caffe model is used (see
% `simplenn_caffe_deploy` for details). Furthermore the script compares
% the execution time of both networks.
%
% Compiled MatCaffe (usually located in `<caffe_dir>/matlab`, built
% with the `matcaffe` target) must be in path.
%
% SIMPLENN_CAFFE_COMPARE(..., 'OPT', VAL, ...) takes the following
% options:
%
% `numRepetitions`:: `1`
% Evaluate the network multiple times. Useful to compare the execution
% time.
%
% `device`:: `cpu`
% Evaluate the network on the specified device (CPU or GPU). For GPU
% evaluation, the current GPU is used for both Caffe and simplenn.
%
% `silent`:: `false`
% When true, supress all outputs to stdin.
%
% See Also: simplenn_caffe_deploy
% Copyright (C) 2016 Karel Lenc, Zohar Bar-Yehuda
% 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).
opts.numRepetitions = 1;
opts.randScale = 100;
opts.device = 'cpu';
opts.silent = false;
opts = vl_argparse(opts, varargin);
info = @(varargin) fprintf(1, varargin{:});
if opts.silent, info = @(varargin) []; end;
if ~exist('caffe.Net', 'class'), error('MatCaffe not in path.'); end
prototxtFilename = [caffeModelBaseName '.prototxt'];
if ~exist(prototxtFilename, 'file')
error('Caffe net definition `%s` not found', prototxtFilename);
end;
modelFilename = [caffeModelBaseName '.caffemodel'];
if ~exist(prototxtFilename, 'file')
error('Caffe net model `%s` not found', modelFilename);
end;
meanFilename = [caffeModelBaseName, '_mean_image.binaryproto'];
net = vl_simplenn_tidy(net);
net = vl_simplenn_move(net, opts.device);
netBlobNames = [{'data'}, cellfun(@(l) l.name, net.layers, ...
'UniformOutput', false)];
% Load the Caffe model
caffeNet = caffe.Net(prototxtFilename, modelFilename, 'test');
switch opts.device
case 'cpu'
caffe.set_mode_cpu();
case 'gpu'
caffe.set_mode_gpu();
gpuDev = gpuDevice();
caffe.set_device(gpuDev.Index - 1);
end
caffeBlobNames = caffeNet.blob_names';
[caffeLayerFound, caffe2netres] = ismember(caffeBlobNames, netBlobNames);
info('Found %d matches between simplenn layers and caffe blob names.\n',...
sum(caffeLayerFound));
% If testData not supplied, use random input
imSize = net.meta.normalization.imageSize;
if ~exist('testData', 'var') || isempty(testData)
testData = rand(imSize, 'single') * opts.randScale;
end
if ischar(testData), testData = imread(testData); end
testDataSize = [size(testData), 1, 1];
assert(all(testDataSize(1:3) == imSize(1:3)), 'Invalid test data size.');
testData = single(testData);
dataCaffe = matlab_img_to_caffe(testData);
if isfield(net.meta.normalization, 'averageImage') && ...
~isempty(net.meta.normalization.averageImage)
avImage = net.meta.normalization.averageImage;
if numel(avImage) == imSize(3)
avImage = reshape(avImage, 1, 1, imSize(3));
end
testData = bsxfun(@minus, testData, avImage);
end
% Test MatConvNet model
stime = tic;
for rep = 1:opts.numRepetitions
res = vl_simplenn(net, testData, [], [], 'ConserveMemory', false);
end
info('MatConvNet %s time: %.1f ms.\n', opts.device, ...
toc(stime)/opts.numRepetitions*1000);
if ~isempty(meanFilename) && exist(meanFilename, 'file')
mean_img_caffe = caffe.io.read_mean(meanFilename);
dataCaffe = bsxfun(@minus, dataCaffe, mean_img_caffe);
end
% Test Caffe model
stime = tic;
for rep = 1:opts.numRepetitions
caffeNet.forward({dataCaffe});
end
info('Caffe %s time: %.1f ms.\n', opts.device, ...
toc(stime)/opts.numRepetitions*1000);
diffStats = struct();
for li = 1:numel(caffeBlobNames)
blob = caffeNet.blobs(caffeBlobNames{li});
caffeData = permute(blob.get_data(), [2, 1, 3, 4]);
if li == 1 && size(caffeData, 3) == 3
caffeData = caffeData(:, :, [3, 2, 1]);
end
mcnData = gather(res(caffe2netres(li)).x);
diff = abs(caffeData(:) - mcnData(:));
diffStats.(caffeBlobNames{li}) = [min(diff), mean(diff), max(diff)]';
end
if ~opts.silent
pp = '% 10s % 10s % 10s % 10s\n';
precp = '% 10.2e';
fprintf(pp, 'Layer name', 'Min', 'Mean', 'Max');
for li = 1:numel(caffeBlobNames)
lstats = diffStats.(caffeBlobNames{li});
fprintf(pp, caffeBlobNames{li}, sprintf(precp, lstats(1)), ...
sprintf(precp, lstats(2)), sprintf(precp, lstats(3)));
end
fprintf('\n');
end
end
function img = matlab_img_to_caffe(img)
img = single(img);
% Convert from HxWxCxN to WxHxCxN per Caffe's convention
img = permute(img, [2 1 3 4]);
if size(img,3) == 3
% Convert from RGB to BGR channel order per Caffe's convention
img = img(:,:, [3 2 1], :);
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_train_dag.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/cnn_train_dag.m
| 15,440 |
utf_8
|
78d69d39fb6f236ce9efd43f995dbdae
|
function [net,stats] = cnn_train_dag(net, imdb, getBatch, 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).
addpath(fullfile(vl_rootnn, 'examples'));
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.epochSize = inf;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.solver = [] ; % Empty array means use the default SGD solver
[opts, varargin] = vl_argparse(opts, varargin) ;
if ~isempty(opts.solver)
assert(isa(opts.solver, 'function_handle') && nargout(opts.solver) == 2,...
'Invalid solver; expected a function handle with two outputs.') ;
% Call without input arguments, to get default options
opts.solverOpts = opts.solver() ;
end
opts.momentum = 0.9 ;
opts.saveSolverState = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.derOutputs = {'objective', 1} ;
opts.extractStatsFn = @extractStats ;
opts.plotStatistics = true;
opts.postEpochFn = [] ; % postEpochFn(net,params,state) called after each epoch; can return a new learning rate, 0 to stop, [] for no change
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isscalar(opts.train) && isnumeric(opts.train) && isnan(opts.train)
opts.train = [] ;
end
if isscalar(opts.val) && isnumeric(opts.val) && isnan(opts.val)
opts.val = [] ;
end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
if isempty(opts.derOutputs)
error('DEROUTPUTS must be specified when training.\n') ;
end
end
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.train = params.train(1:min(opts.epochSize, numel(opts.train)));
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(opts.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
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) ;
if opts.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
if ~isempty(opts.postEpochFn)
if nargout(opts.postEpochFn) == 0
opts.postEpochFn(net, params, state) ;
else
lr = opts.postEpochFn(net, params, state) ;
if ~isempty(lr), opts.learningRate = lr; end
if opts.learningRate == 0, break; end
end
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% 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.solverState)
state.solverState = cell(1, numel(net.params)) ;
state.solverState(:) = {0} ;
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net.move('gpu') ;
for i = 1:numel(state.solverState)
s = state.solverState{i} ;
if isnumeric(s)
state.solverState{i} = gpuArray(s) ;
elseif isstruct(s)
state.solverState{i} = structfun(@gpuArray, s, 'UniformOutput', false) ;
end
end
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 ;
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) ;
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(params.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(params.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
% Get statistics.
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats.num = num ;
stats.time = time ;
stats = params.extractStatsFn(stats,net) ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
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.saveSolverState
state.solverState = [] ;
else
for i = 1:numel(state.solverState)
s = state.solverState{i} ;
if isnumeric(s)
state.solverState{i} = gather(s) ;
elseif isstruct(s)
state.solverState{i} = structfun(@gather, s, 'UniformOutput', false) ;
end
end
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 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) ;
case 'gradient'
thisDecay = params.weightDecay * net.params(p).weightDecay ;
thisLR = params.learningRate * net.params(p).learningRate ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.params(p).value) ;
if isempty(params.solver)
% Default solver is the optimised SGD.
% Update momentum.
state.solverState{p} = vl_taccum(...
params.momentum, state.solverState{p}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = params.momentum * state.solverState{p} - parDer ;
else
delta = state.solverState{p} ;
end
% Update parameters.
net.params(p).value = vl_taccum(...
1, net.params(p).value, thisLR, delta) ;
else
% call solver function to update weights
[net.params(p).value, state.solverState{p}] = ...
params.solver(net.params(p).value, state.solverState{p}, ...
parDer, params.solverOpts, thisLR) ;
end
end
otherwise
error('Unknown training method ''%s'' for parameter ''%s''.', ...
net.params(p).trainMethod, ...
net.params(p).name) ;
end
end
% -------------------------------------------------------------------------
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)
if net.layers(sel(i)).block.ignoreAverage, continue; end;
stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net_, state)
% -------------------------------------------------------------------------
net = net_.saveobj() ;
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
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)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
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
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_train.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/cnn_train.m
| 21,052 |
utf_8
|
355e8041424653a50b61ea9730fb9d11
|
function [net, stats] = cnn_train(net, imdb, getBatch, varargin)
%CNN_TRAIN An example implementation of SGD for training CNNs
% CNN_TRAIN() is an example learner implementing stochastic
% gradient descent with momentum to train a CNN. It can be used
% with different datasets and tasks by providing a suitable
% getBatch function.
%
% 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).
addpath(fullfile(vl_rootnn, 'examples'));
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.epochSize = inf;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.solver = [] ; % Empty array means use the default SGD solver
[opts, varargin] = vl_argparse(opts, varargin) ;
if ~isempty(opts.solver)
assert(isa(opts.solver, 'function_handle') && nargout(opts.solver) == 2,...
'Invalid solver; expected a function handle with two outputs.') ;
% Call without input arguments, to get default options
opts.solverOpts = opts.solver() ;
end
opts.momentum = 0.9 ;
opts.saveSolverState = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.conserveMemory = true ;
opts.backPropDepth = +inf ;
opts.sync = false ;
opts.cudnn = true ;
opts.errorFunction = 'multiclass' ;
opts.errorLabels = {} ;
opts.plotDiagnostics = false ;
opts.plotStatistics = true;
opts.postEpochFn = [] ; % postEpochFn(net,params,state) called after each epoch; can return a new learning rate, 0 to stop, [] for no change
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isscalar(opts.train) && isnumeric(opts.train) && isnan(opts.train)
opts.train = [] ;
end
if isscalar(opts.val) && isnumeric(opts.val) && isnan(opts.val)
opts.val = [] ;
end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
net = vl_simplenn_tidy(net); % fill in some eventually missing values
net.layers{end-1}.precious = 1; % do not remove predictions, used for error
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
for i=1:numel(net.layers)
J = numel(net.layers{i}.weights) ;
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, J) ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = ones(1, J) ;
end
end
end
% setup error calculation function
hasError = true ;
if isstr(opts.errorFunction)
switch opts.errorFunction
case 'none'
opts.errorFunction = @error_none ;
hasError = false ;
case 'multiclass'
opts.errorFunction = @error_multiclass ;
if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end
case 'binary'
opts.errorFunction = @error_binary ;
if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end
otherwise
error('Unknown error function ''%s''.', opts.errorFunction) ;
end
end
state.getBatch = getBatch ;
stats = [] ;
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.train = params.train(1:min(opts.epochSize, numel(opts.train)));
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(params.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
if ~evaluateMode
saveStats(modelPath(epoch), stats) ;
end
if params.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
if ~isempty(opts.postEpochFn)
if nargout(opts.postEpochFn) == 0
opts.postEpochFn(net, params, state) ;
else
lr = opts.postEpochFn(net, params, state) ;
if ~isempty(lr), opts.learningRate = lr; end
if opts.learningRate == 0, break; end
end
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function err = error_multiclass(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
[~,predictions] = sort(predictions, 3, 'descend') ;
% be resilient to badly formatted labels
if numel(labels) == size(predictions, 4)
labels = reshape(labels,1,1,1,[]) ;
end
% skip null labels
mass = single(labels(:,:,1,:) > 0) ;
if size(labels,3) == 2
% if there is a second channel in labels, used it as weights
mass = mass .* labels(:,:,2,:) ;
labels(:,:,2,:) = [] ;
end
m = min(5, size(predictions,3)) ;
error = ~bsxfun(@eq, predictions, labels) ;
err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;
err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;
% -------------------------------------------------------------------------
function err = error_binary(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
error = bsxfun(@times, predictions, labels) < 0 ;
err = sum(error(:)) ;
% -------------------------------------------------------------------------
function err = error_none(params, labels, res)
% -------------------------------------------------------------------------
err = zeros(0,1) ;
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% 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.solverState)
for i = 1:numel(net.layers)
state.solverState{i} = cell(1, numel(net.layers{i}.weights)) ;
state.solverState{i}(:) = {0} ;
end
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net = vl_simplenn_move(net, 'gpu') ;
for i = 1:numel(state.solverState)
for j = 1:numel(state.solverState{i})
s = state.solverState{i}{j} ;
if isnumeric(s)
state.solverState{i}{j} = gpuArray(s) ;
elseif isstruct(s)
state.solverState{i}{j} = structfun(@gpuArray, s, 'UniformOutput', false) ;
end
end
end
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
vl_simplenn_start_parserv(net, parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
subset = params.(mode) ;
num = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
adjustTime = 0 ;
res = [] ;
error = [] ;
start = tic ;
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 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
[im, labels] = params.getBatch(params.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(params.imdb, nextBatch) ;
end
if numGpus >= 1
im = gpuArray(im) ;
end
if strcmp(mode, 'train')
dzdy = 1 ;
evalMode = 'normal' ;
else
dzdy = [] ;
evalMode = 'test' ;
end
net.layers{end}.class = labels ;
res = vl_simplenn(net, im, dzdy, res, ...
'accumulate', s ~= 1, ...
'mode', evalMode, ...
'conserveMemory', params.conserveMemory, ...
'backPropDepth', params.backPropDepth, ...
'sync', params.sync, ...
'cudnn', params.cudnn, ...
'parameterServer', parserv, ...
'holdOn', s < params.numSubBatches) ;
% accumulate errors
error = sum([error, [...
sum(double(gather(res(end).x))) ;
reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;
end
% accumulate gradient
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
[net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;
end
% get statistics
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats = extractStats(net, params, error / num) ;
stats.num = num ;
stats.time = time ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
% collect diagnostic statistics
if strcmp(mode, 'train') && params.plotDiagnostics
switchFigure(2) ; clf ;
diagn = [res.stats] ;
diagnvar = horzcat(diagn.variation) ;
diagnpow = horzcat(diagn.power) ;
subplot(2,2,1) ; barh(diagnvar) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnvar), ...
'YTickLabel',horzcat(diagn.label), ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1], ...
'XTick', 10.^(-5:1)) ;
grid on ; title('Variation');
subplot(2,2,2) ; barh(sqrt(diagnpow)) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnpow), ...
'YTickLabel',{diagn.powerLabel}, ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1e5], ...
'XTick', 10.^(-5:5)) ;
grid on ; title('Power');
subplot(2,2,3); plot(squeeze(res(end-1).x)) ;
drawnow ;
end
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.saveSolverState
state.solverState = [] ;
else
for i = 1:numel(state.solverState)
for j = 1:numel(state.solverState{i})
s = state.solverState{i}{j} ;
if isnumeric(s)
state.solverState{i}{j} = gather(s) ;
elseif isstruct(s)
state.solverState{i}{j} = structfun(@gather, s, 'UniformOutput', false) ;
end
end
end
end
net = vl_simplenn_move(net, 'cpu') ;
% -------------------------------------------------------------------------
function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for l=numel(net.layers):-1:1
for j=numel(res(l).dzdw):-1:1
if ~isempty(parserv)
tag = sprintf('l%d_%d',l,j) ;
parDer = parserv.pull(tag) ;
else
parDer = res(l).dzdw{j} ;
end
if j == 3 && strcmp(net.layers{l}.type, 'bnorm')
% special case for learning bnorm moments
thisLR = net.layers{l}.learningRate(j) ;
net.layers{l}.weights{j} = vl_taccum(...
1 - thisLR, ...
net.layers{l}.weights{j}, ...
thisLR / batchSize, ...
parDer) ;
else
% Standard gradient training.
thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;
thisLR = params.learningRate * net.layers{l}.learningRate(j) ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.layers{l}.weights{j}) ;
if isempty(params.solver)
% Default solver is the optimised SGD.
% Update momentum.
state.solverState{l}{j} = vl_taccum(...
params.momentum, state.solverState{l}{j}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = params.momentum * state.solverState{l}{j} - parDer ;
else
delta = state.solverState{l}{j} ;
end
% Update parameters.
net.layers{l}.weights{j} = vl_taccum(...
1, net.layers{l}.weights{j}, ...
thisLR, delta) ;
else
% call solver function to update weights
[net.layers{l}.weights{j}, state.solverState{l}{j}] = ...
params.solver(net.layers{l}.weights{j}, state.solverState{l}{j}, ...
parDer, params.solverOpts, thisLR) ;
end
end
end
% if requested, collect some useful stats for debugging
if params.plotDiagnostics
variation = [] ;
label = '' ;
switch net.layers{l}.type
case {'conv','convt'}
if isnumeric(state.solverState{l}{j})
variation = thisLR * mean(abs(state.solverState{l}{j}(:))) ;
end
power = mean(res(l+1).x(:).^2) ;
if j == 1 % fiters
base = mean(net.layers{l}.weights{j}(:).^2) ;
label = 'filters' ;
else % biases
base = sqrt(power) ;%mean(abs(res(l+1).x(:))) ;
label = 'biases' ;
end
variation = variation / base ;
label = sprintf('%s_%s', net.layers{l}.name, label) ;
end
res(l).stats.variation(j) = variation ;
res(l).stats.power = power ;
res(l).stats.powerLabel = net.layers{l}.name ;
res(l).stats.label{j} = label ;
end
end
end
% -------------------------------------------------------------------------
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(net, params, errors)
% -------------------------------------------------------------------------
stats.objective = errors(1) ;
for i = 1:numel(params.errorLabels)
stats.(params.errorLabels{i}) = errors(i+1) ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net, state)
% -------------------------------------------------------------------------
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = vl_simplenn_tidy(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
%clear vl_tmove vl_imreadjpeg ;
disp('Clearing mex files') ;
clear mex ;
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(params, cold)
% -------------------------------------------------------------------------
numGpus = numel(params.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
disp(gpuDevice(params.gpus)) ;
else
spmd
clearMex() ;
disp(gpuDevice(params.gpus(labindex))) ;
end
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_stn_cluttered_mnist.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/spatial_transformer/cnn_stn_cluttered_mnist.m
| 3,872 |
utf_8
|
3235801f70028cc27d54d15ec2964808
|
function [net, info] = cnn_stn_cluttered_mnist(varargin)
%CNN_STN_CLUTTERED_MNIST Demonstrates training a spatial transformer
% The spatial transformer network (STN) is trained on the
% cluttered MNIST dataset.
run(fullfile(fileparts(mfilename('fullpath')),...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile(vl_rootnn, 'data') ;
opts.useSpatialTransformer = true ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataPath = fullfile(opts.dataDir,'cluttered-mnist.mat') ;
if opts.useSpatialTransformer
opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-stn') ;
else
opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-no-stn') ;
end
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.dataURL = 'http://www.vlfeat.org/matconvnet/download/data/cluttered-mnist.mat' ;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% --------------------------------------------------------------------
% Prepare data
% --------------------------------------------------------------------
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getImdDB(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net = cnn_stn_cluttered_mnist_init([60 60], true) ; % initialize the network
net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
fbatch = @(i,b) getBatch(opts.train,i,b);
[net, info] = cnn_train_dag(net, imdb, fbatch, ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 2)) ;
% --------------------------------------------------------------------
% Show transformer
% --------------------------------------------------------------------
figure(100) ; clf ;
v = net.getVarIndex('xST') ;
net.vars(v).precious = true ;
net.eval({'input',imdb.images.data(:,:,:,1:6)}) ;
for t = 1:6
subplot(2,6,t) ; imagesc(imdb.images.data(:,:,:,t)) ; axis image off ;
subplot(2,6,6+t) ; imagesc(net.vars(v).value(:,:,:,t)) ; axis image off ;
colormap gray ;
end
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
if ~isa(imdb.images.data, 'gpuArray') && numel(opts.gpus) > 0
imdb.images.data = gpuArray(imdb.images.data);
imdb.images.labels = gpuArray(imdb.images.labels);
end
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
inputs = {'input', images, 'label', labels} ;
% --------------------------------------------------------------------
function imdb = getImdDB(opts)
% --------------------------------------------------------------------
% Prepare the IMDB structure:
if ~exist(opts.dataDir, 'dir')
mkdir(opts.dataDir) ;
end
if ~exist(opts.dataPath)
fprintf('Downloading %s to %s.\n', opts.dataURL, opts.dataPath) ;
urlwrite(opts.dataURL, opts.dataPath) ;
end
dat = load(opts.dataPath);
set = [ones(1,numel(dat.y_tr)) 2*ones(1,numel(dat.y_vl)) 3*ones(1,numel(dat.y_ts))];
data = single(cat(4,dat.x_tr,dat.x_vl,dat.x_ts));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, dat.y_tr,dat.y_vl,dat.y_ts)) ;
imdb.images.set = set ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
|
github
|
maxkferg/casting-defect-detection-master
|
fast_rcnn_train.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/fast_rcnn/fast_rcnn_train.m
| 6,399 |
utf_8
|
54b0bc7fa26d672ed6673d3f1832944e
|
function [net, info] = fast_rcnn_train(varargin)
%FAST_RCNN_TRAIN Demonstrates training a Fast-RCNN detector
% Copyright (C) 2016 Hakan Bilen.
% 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).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
addpath(fullfile(vl_rootnn,'examples','fast_rcnn','bbox_functions'));
addpath(fullfile(vl_rootnn,'examples','fast_rcnn','datasets'));
opts.dataDir = fullfile(vl_rootnn, 'data') ;
opts.sswDir = fullfile(vl_rootnn, 'data', 'SSW');
opts.expDir = fullfile(vl_rootnn, 'data', 'fast-rcnn-vgg16-pascal07') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.modelPath = fullfile(opts.dataDir, 'models', ...
'imagenet-vgg-verydeep-16.mat') ;
opts.piecewise = true; % piecewise training (+bbox regression)
opts.train.gpus = [] ;
opts.train.batchSize = 2 ;
opts.train.numSubBatches = 1 ;
opts.train.continue = true ;
opts.train.prefetch = false ; % does not help for two images in a batch
opts.train.learningRate = 1e-3 / 64 * [ones(1,6) 0.1*ones(1,6)];
opts.train.weightDecay = 0.0005 ;
opts.train.numEpochs = 12 ;
opts.train.derOutputs = {'losscls', 1, 'lossbbox', 1} ;
opts.lite = false ;
opts.numFetchThreads = 2 ;
opts = vl_argparse(opts, varargin) ;
display(opts);
opts.train.expDir = opts.expDir ;
opts.train.numEpochs = numel(opts.train.learningRate) ;
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = fast_rcnn_init(...
'piecewise',opts.piecewise,...
'modelPath',opts.modelPath);
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath,'file') == 2
fprintf('Loading imdb...');
imdb = load(opts.imdbPath) ;
else
if ~exist(opts.expDir,'dir')
mkdir(opts.expDir);
end
fprintf('Setting VOC2007 up, this may take a few minutes\n');
imdb = cnn_setup_data_voc07_ssw(...
'dataDir', opts.dataDir, ...
'sswDir', opts.sswDir, ...
'addFlipped', true, ...
'useDifficult', true) ;
save(opts.imdbPath,'-struct', 'imdb','-v7.3');
fprintf('\n');
end
fprintf('done\n');
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
% use train + val split to train
imdb.images.set(imdb.images.set == 2) = 1;
% minibatch options
bopts = net.meta.normalization;
bopts.useGpu = numel(opts.train.gpus) > 0 ;
bopts.numFgRoisPerImg = 16;
bopts.numRoisPerImg = 64;
bopts.maxScale = 1000;
bopts.scale = 600;
bopts.bgLabel = numel(imdb.classes.name)+1;
bopts.visualize = 0;
bopts.interpolation = net.meta.normalization.interpolation;
bopts.numThreads = opts.numFetchThreads;
bopts.prefetch = opts.train.prefetch;
[net,info] = cnn_train_dag(net, imdb, @(i,b) ...
getBatch(bopts,i,b), ...
opts.train) ;
% --------------------------------------------------------------------
% Deploy
% --------------------------------------------------------------------
modelPath = fullfile(opts.expDir, 'net-deployed.mat');
if ~exist(modelPath,'file')
net = deployFRCNN(net,imdb);
net_ = net.saveobj() ;
save(modelPath, '-struct', 'net_') ;
clear net_ ;
end
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
opts.visualize = 0;
if isempty(batch)
return;
end
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
opts.prefetch = (nargout == 0);
[im,rois,labels,btargets] = fast_rcnn_train_get_batch(images,imdb,...
batch, opts);
if opts.prefetch, return; end
nb = numel(labels);
nc = numel(imdb.classes.name) + 1;
% regression error only for positives
instance_weights = zeros(1,1,4*nc,nb,'single');
targets = zeros(1,1,4*nc,nb,'single');
for b=1:nb
if labels(b)>0 && labels(b)~=opts.bgLabel
targets(1,1,4*(labels(b)-1)+1:4*labels(b),b) = btargets(b,:)';
instance_weights(1,1,4*(labels(b)-1)+1:4*labels(b),b) = 1;
end
end
rois = single(rois);
if opts.useGpu > 0
im = gpuArray(im) ;
rois = gpuArray(rois) ;
targets = gpuArray(targets) ;
instance_weights = gpuArray(instance_weights) ;
end
inputs = {'input', im, 'label', labels, 'rois', rois, 'targets', targets, ...
'instance_weights', instance_weights} ;
% --------------------------------------------------------------------
function net = deployFRCNN(net,imdb)
% --------------------------------------------------------------------
% function net = deployFRCNN(net)
for l = numel(net.layers):-1:1
if isa(net.layers(l).block, 'dagnn.Loss') || ...
isa(net.layers(l).block, 'dagnn.DropOut')
layer = net.layers(l);
net.removeLayer(layer.name);
net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;
end
end
net.rebuild();
pfc8 = net.getLayerIndex('predcls') ;
net.addLayer('probcls',dagnn.SoftMax(),net.layers(pfc8).outputs{1},...
'probcls',{});
net.vars(net.getVarIndex('probcls')).precious = true ;
idxBox = net.getLayerIndex('predbbox') ;
if ~isnan(idxBox)
net.vars(net.layers(idxBox).outputIndexes(1)).precious = true ;
% incorporate mean and std to bbox regression parameters
blayer = net.layers(idxBox) ;
filters = net.params(net.getParamIndex(blayer.params{1})).value ;
biases = net.params(net.getParamIndex(blayer.params{2})).value ;
boxMeans = single(imdb.boxes.bboxMeanStd{1}');
boxStds = single(imdb.boxes.bboxMeanStd{2}');
net.params(net.getParamIndex(blayer.params{1})).value = ...
bsxfun(@times,filters,...
reshape([boxStds(:)' zeros(1,4,'single')]',...
[1 1 1 4*numel(net.meta.classes.name)]));
biases = biases .* [boxStds(:)' zeros(1,4,'single')];
net.params(net.getParamIndex(blayer.params{2})).value = ...
bsxfun(@plus,biases, [boxMeans(:)' zeros(1,4,'single')]);
end
net.mode = 'test' ;
|
github
|
maxkferg/casting-defect-detection-master
|
fast_rcnn_evaluate.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/fast_rcnn/fast_rcnn_evaluate.m
| 6,941 |
utf_8
|
a54a3f8c3c8e5a8ff7ebe4e2b12ede30
|
function [aps, speed] = fast_rcnn_evaluate(varargin)
%FAST_RCNN_EVALUATE Evaluate a trained Fast-RCNN model on PASCAL VOC 2007
% Copyright (C) 2016 Hakan Bilen.
% 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).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
addpath(fullfile(vl_rootnn, 'data', 'VOCdevkit', 'VOCcode'));
addpath(genpath(fullfile(vl_rootnn, 'examples', 'fast_rcnn')));
opts.dataDir = fullfile(vl_rootnn, 'data') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.sswDir = fullfile(opts.dataDir, 'SSW');
opts.expDir = fullfile(opts.dataDir, 'fast-rcnn-vgg16-pascal07') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.modelPath = fullfile(opts.expDir, 'net-deployed.mat') ;
opts.gpu = [] ;
opts.numFetchThreads = 1 ;
opts.nmsThresh = 0.3 ;
opts.maxPerImage = 100 ;
opts = vl_argparse(opts, varargin) ;
display(opts) ;
if ~exist(opts.expDir,'dir')
mkdir(opts.expDir) ;
end
if ~isempty(opts.gpu)
gpuDevice(opts.gpu)
end
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = dagnn.DagNN.loadobj(load(opts.modelPath)) ;
net.mode = 'test' ;
if ~isempty(opts.gpu)
net.move('gpu') ;
end
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath,'file')
fprintf('Loading precomputed imdb...\n');
imdb = load(opts.imdbPath) ;
else
fprintf('Obtaining dataset and imdb...\n');
imdb = cnn_setup_data_voc07_ssw(...
'dataDir',opts.dataDir,...
'sswDir',opts.sswDir);
save(opts.imdbPath,'-struct', 'imdb','-v7.3');
end
fprintf('done\n');
bopts.averageImage = net.meta.normalization.averageImage;
bopts.useGpu = numel(opts.gpu) > 0 ;
bopts.maxScale = 1000;
bopts.bgLabel = 21;
bopts.visualize = 0;
bopts.scale = 600;
bopts.interpolation = net.meta.normalization.interpolation;
bopts.numThreads = opts.numFetchThreads;
% -------------------------------------------------------------------------
% Evaluate
% -------------------------------------------------------------------------
VOCinit;
VOCopts.testset='test';
testIdx = find(imdb.images.set == 3) ;
cls_probs = cell(1,numel(testIdx)) ;
box_deltas = cell(1,numel(testIdx)) ;
boxscores_nms = cell(numel(VOCopts.classes),numel(testIdx)) ;
ids = cell(numel(VOCopts.classes),numel(testIdx)) ;
dataVar = 'input' ;
probVarI = net.getVarIndex('probcls') ;
boxVarI = net.getVarIndex('predbbox') ;
if isnan(probVarI)
dataVar = 'data' ;
probVarI = net.getVarIndex('cls_prob') ;
boxVarI = net.getVarIndex('bbox_pred') ;
end
net.vars(probVarI).precious = true ;
net.vars(boxVarI).precious = true ;
start = tic ;
for t=1:numel(testIdx)
speed = t/toc(start) ;
fprintf('Image %d of %d (%.f HZ)\n', t, numel(testIdx), speed) ;
batch = testIdx(t);
inputs = getBatch(bopts, imdb, batch);
inputs{1} = dataVar ;
net.eval(inputs) ;
cls_probs{t} = squeeze(gather(net.vars(probVarI).value)) ;
box_deltas{t} = squeeze(gather(net.vars(boxVarI).value)) ;
end
% heuristic: keep an average of 40 detections per class per images prior
% to NMS
max_per_set = 40 * numel(testIdx);
% detection thresold for each class (this is adaptively set based on the
% max_per_set constraint)
cls_thresholds = zeros(1,numel(VOCopts.classes));
cls_probs_concat = horzcat(cls_probs{:});
for c = 1:numel(VOCopts.classes)
q = find(strcmp(VOCopts.classes{c}, net.meta.classes.name)) ;
so = sort(cls_probs_concat(q,:),'descend');
cls_thresholds(q) = so(min(max_per_set,numel(so)));
fprintf('Applying NMS for %s\n',VOCopts.classes{c});
for t=1:numel(testIdx)
si = find(cls_probs{t}(q,:) >= cls_thresholds(q)) ;
if isempty(si), continue; end
cls_prob = cls_probs{t}(q,si)';
pbox = imdb.boxes.pbox{testIdx(t)}(si,:);
% back-transform bounding box corrections
delta = box_deltas{t}(4*(q-1)+1:4*q,si)';
pred_box = bbox_transform_inv(pbox, delta);
im_size = imdb.images.size(testIdx(t),[2 1]);
pred_box = bbox_clip(round(pred_box), im_size);
% Threshold. Heuristic: keep at most 100 detection per class per image
% prior to NMS.
boxscore = [pred_box cls_prob];
[~,si] = sort(boxscore(:,5),'descend');
boxscore = boxscore(si,:);
boxscore = boxscore(1:min(size(boxscore,1),opts.maxPerImage),:);
% NMS
pick = bbox_nms(double(boxscore),opts.nmsThresh);
boxscores_nms{c,t} = boxscore(pick,:) ;
ids{c,t} = repmat({imdb.images.name{testIdx(t)}(1:end-4)},numel(pick),1) ;
if 0
figure(1) ; clf ;
idx = boxscores_nms{c,t}(:,5)>0.5;
if sum(idx)==0, continue; end
bbox_draw(imread(fullfile(imdb.imageDir,imdb.images.name{testIdx(t)})), ...
boxscores_nms{c,t}(idx,:)) ;
title(net.meta.classes.name{q}) ;
drawnow ;
pause;
%keyboard
end
end
end
%% PASCAL VOC evaluation
VOCdevkitPath = fullfile(vl_rootnn,'data','VOCdevkit');
aps = zeros(numel(VOCopts.classes),1);
% fix voc folders
VOCopts.imgsetpath = fullfile(VOCdevkitPath,'VOC2007','ImageSets','Main','%s.txt');
VOCopts.annopath = fullfile(VOCdevkitPath,'VOC2007','Annotations','%s.xml');
VOCopts.localdir = fullfile(VOCdevkitPath,'local','VOC2007');
VOCopts.detrespath = fullfile(VOCdevkitPath, 'results', 'VOC2007', 'Main', ['%s_det_', VOCopts.testset, '_%s.txt']);
% write det results to txt files
for c=1:numel(VOCopts.classes)
fid = fopen(sprintf(VOCopts.detrespath,'comp3',VOCopts.classes{c}),'w');
for i=1:numel(testIdx)
if isempty(boxscores_nms{c,i}), continue; end
dets = boxscores_nms{c,i};
for j=1:size(dets,1)
fprintf(fid,'%s %.6f %d %d %d %d\n', ...
imdb.images.name{testIdx(i)}(1:end-4), ...
dets(j,5),dets(j,1:4)) ;
end
end
fclose(fid);
[rec,prec,ap] = VOCevaldet(VOCopts,'comp3',VOCopts.classes{c},0);
fprintf('%s ap %.1f\n',VOCopts.classes{c},100*ap);
aps(c) = ap;
end
fprintf('mean ap %.1f\n',100*mean(aps));
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
if isempty(batch)
return;
end
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
opts.prefetch = (nargout == 0);
[im,rois] = fast_rcnn_eval_get_batch(images, imdb, batch, opts);
rois = single(rois);
if opts.useGpu > 0
im = gpuArray(im) ;
rois = gpuArray(rois) ;
end
inputs = {'input', im, 'rois', rois} ;
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_cifar.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/cifar/cnn_cifar.m
| 5,334 |
utf_8
|
eb9aa887d804ee635c4295a7a397206f
|
function [net, info] = cnn_cifar(varargin)
% CNN_CIFAR Demonstrates MatConvNet on CIFAR-10
% The demo includes two standard model: LeNet and Network in
% Network (NIN). Use the 'modelType' option to choose one.
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.modelType = 'lenet' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.expDir = fullfile(vl_rootnn, 'data', ...
sprintf('cifar-%s', opts.modelType)) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile(vl_rootnn, 'data','cifar') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.whitenData = true ;
opts.contrastNormalization = true ;
opts.networkType = 'simplenn' ;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare model and data
% -------------------------------------------------------------------------
switch opts.modelType
case 'lenet'
net = cnn_cifar_init('networkType', opts.networkType) ;
case 'nin'
net = cnn_cifar_init_nin('networkType', opts.networkType) ;
otherwise
error('Unknown model type ''%s''.', opts.modelType) ;
end
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getCifarImdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net.meta.classes.name = imdb.meta.classes(:)' ;
% -------------------------------------------------------------------------
% Train
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainfn = @cnn_train ;
case 'dagnn', trainfn = @cnn_train_dag ;
end
[net, info] = trainfn(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
% -------------------------------------------------------------------------
function fn = getBatch(opts)
% -------------------------------------------------------------------------
switch lower(opts.networkType)
case 'simplenn'
fn = @(x,y) getSimpleNNBatch(x,y) ;
case 'dagnn'
bopts = struct('numGpus', numel(opts.train.gpus)) ;
fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end
% -------------------------------------------------------------------------
function [images, labels] = getSimpleNNBatch(imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if rand > 0.5, images=fliplr(images) ; end
% -------------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if rand > 0.5, images=fliplr(images) ; end
if opts.numGpus > 0
images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;
% -------------------------------------------------------------------------
function imdb = getCifarImdb(opts)
% -------------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
unpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');
files = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...
{'test_batch.mat'}];
files = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);
file_set = uint8([ones(1, 5), 3]);
if any(cellfun(@(fn) ~exist(fn, 'file'), files))
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;
fprintf('downloading %s\n', url) ;
untar(url, opts.dataDir) ;
end
data = cell(1, numel(files));
labels = cell(1, numel(files));
sets = cell(1, numel(files));
for fi = 1:numel(files)
fd = load(files{fi}) ;
data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;
labels{fi} = fd.labels' + 1; % Index from 1
sets{fi} = repmat(file_set(fi), size(labels{fi}));
end
set = cat(2, sets{:});
data = single(cat(4, data{:}));
% remove mean in any case
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean);
% normalize by image mean and std as suggested in `An Analysis of
% Single-Layer Networks in Unsupervised Feature Learning` Adam
% Coates, Honglak Lee, Andrew Y. Ng
if opts.contrastNormalization
z = reshape(data,[],60000) ;
z = bsxfun(@minus, z, mean(z,1)) ;
n = std(z,0,1) ;
z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ;
data = reshape(z, 32, 32, 3, []) ;
end
if opts.whitenData
z = reshape(data,[],60000) ;
W = z(:,set == 1)*z(:,set == 1)'/60000 ;
[V,D] = eig(W) ;
% the scale is selected to approximately preserve the norm of W
d2 = diag(D) ;
en = sqrt(mean(d2)) ;
z = V*diag(en./max(sqrt(d2), 10))*V'*z ;
data = reshape(z, 32, 32, 3, []) ;
end
clNames = load(fullfile(unpackPath, 'batches.meta.mat'));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, labels{:})) ;
imdb.images.set = set;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = clNames.label_names;
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_cifar_init_nin.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/cifar/cnn_cifar_init_nin.m
| 5,561 |
utf_8
|
aca711e04a8cd82821f658922218368c
|
function net = cnn_cifar_init_nin(varargin)
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;
% CIFAR-10 model from
% M. Lin, Q. Chen, and S. Yan. Network in network. CoRR,
% abs/1312.4400, 2013.
%
% It reproduces the NIN + Dropout result of Table 1 (<= 10.41% top1 error).
net.layers = {} ;
lr = [1 10] ;
% Block 1
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv1', ...
'weights', {init_weights(5,3,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 2) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu1') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp1', ...
'weights', {init_weights(1,192,160)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp1') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp2', ...
'weights', {init_weights(1,160,96)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp2') ;
net.layers{end+1} = struct('name', 'pool1', ...
'type', 'pool', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout1', 'rate', 0.5) ;
% Block 2
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv2', ...
'weights', {init_weights(5,96,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 2) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu2') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp3', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp3') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp4', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp4') ;
net.layers{end+1} = struct('name', 'pool2', ...
'type', 'pool', ...
'method', 'avg', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout2', 'rate', 0.5) ;
% Block 3
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv3', ...
'weights', {init_weights(3,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 1) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu3') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp5', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp5') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp6', ...
'weights', {init_weights(1,192,10)}, ...
'learningRate', 0.001*lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end}.weights{1} = 0.1 * net.layers{end}.weights{1} ;
%net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp6') ;
net.layers{end+1} = struct('type', 'pool', ...
'name', 'pool3', ...
'method', 'avg', ...
'pool', [7 7], ...
'stride', 1, ...
'pad', 0) ;
% Loss layer
net.layers{end+1} = struct('type', 'softmaxloss') ;
% Meta parameters
net.meta.inputSize = [32 32 3] ;
net.meta.trainOpts.learningRate = [0.002, 0.01, 0.02, 0.04 * ones(1,80), 0.004 * ones(1,10), 0.0004 * ones(1,10)] ;
net.meta.trainOpts.weightDecay = 0.0005 ;
net.meta.trainOpts.batchSize = 100 ;
net.meta.trainOpts.numEpochs = numel(net.meta.trainOpts.learningRate) ;
% Fill in default values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('error', dagnn.Loss('loss', 'classerror'), ...
{'prediction','label'}, 'error') ;
otherwise
assert(false) ;
end
function weights = init_weights(k,m,n)
weights{1} = randn(k,k,m,n,'single') * sqrt(2/(k*k*m)) ;
weights{2} = zeros(n,1,'single') ;
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_imagenet_init_resnet.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/imagenet/cnn_imagenet_init_resnet.m
| 6,717 |
utf_8
|
aa905a97830e90dc7d33f75ad078301e
|
function net = cnn_imagenet_init_resnet(varargin)
%CNN_IMAGENET_INIT_RESNET Initialize the ResNet-50 model for ImageNet classification
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.averageImage = zeros(3,1) ;
opts.colorDeviation = zeros(3) ;
opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB
opts = vl_argparse(opts, varargin) ;
net = dagnn.DagNN() ;
lastAdded.var = 'input' ;
lastAdded.depth = 3 ;
function Conv(name, ksize, depth, varargin)
% Helper function to add a Convolutional + BatchNorm + ReLU
% sequence to the network.
args.relu = true ;
args.downsample = false ;
args.bias = false ;
args = vl_argparse(args, varargin) ;
if args.downsample, stride = 2 ; else stride = 1 ; end
if args.bias, pars = {[name '_f'], [name '_b']} ; else pars = {[name '_f']} ; end
net.addLayer([name '_conv'], ...
dagnn.Conv('size', [ksize ksize lastAdded.depth depth], ...
'stride', stride, ....
'pad', (ksize - 1) / 2, ...
'hasBias', args.bias, ...
'opts', {'cudnnworkspacelimit', opts.cudnnWorkspaceLimit}), ...
lastAdded.var, ...
[name '_conv'], ...
pars) ;
net.addLayer([name '_bn'], ...
dagnn.BatchNorm('numChannels', depth, 'epsilon', 1e-5), ...
[name '_conv'], ...
[name '_bn'], ...
{[name '_bn_w'], [name '_bn_b'], [name '_bn_m']}) ;
lastAdded.depth = depth ;
lastAdded.var = [name '_bn'] ;
if args.relu
net.addLayer([name '_relu'] , ...
dagnn.ReLU(), ...
lastAdded.var, ...
[name '_relu']) ;
lastAdded.var = [name '_relu'] ;
end
end
% -------------------------------------------------------------------------
% Add input section
% -------------------------------------------------------------------------
Conv('conv1', 7, 64, ...
'relu', true, ...
'bias', false, ...
'downsample', true) ;
net.addLayer(...
'conv1_pool' , ...
dagnn.Pooling('poolSize', [3 3], ...
'stride', 2, ...
'pad', 1, ...
'method', 'max'), ...
lastAdded.var, ...
'conv1') ;
lastAdded.var = 'conv1' ;
% -------------------------------------------------------------------------
% Add intermediate sections
% -------------------------------------------------------------------------
for s = 2:5
switch s
case 2, sectionLen = 3 ;
case 3, sectionLen = 4 ; % 8 ;
case 4, sectionLen = 6 ; % 23 ; % 36 ;
case 5, sectionLen = 3 ;
end
% -----------------------------------------------------------------------
% Add intermediate segments for each section
for l = 1:sectionLen
depth = 2^(s+4) ;
sectionInput = lastAdded ;
name = sprintf('conv%d_%d', s, l) ;
% Optional adapter layer
if l == 1
Conv([name '_adapt_conv'], 1, 2^(s+6), 'downsample', s >= 3, 'relu', false) ;
end
sumInput = lastAdded ;
% ABC: 1x1, 3x3, 1x1; downsample if first segment in section from
% section 2 onwards.
lastAdded = sectionInput ;
%Conv([name 'a'], 1, 2^(s+4), 'downsample', (s >= 3) & l == 1) ;
%Conv([name 'b'], 3, 2^(s+4)) ;
Conv([name 'a'], 1, 2^(s+4)) ;
Conv([name 'b'], 3, 2^(s+4), 'downsample', (s >= 3) & l == 1) ;
Conv([name 'c'], 1, 2^(s+6), 'relu', false) ;
% Sum layer
net.addLayer([name '_sum'] , ...
dagnn.Sum(), ...
{sumInput.var, lastAdded.var}, ...
[name '_sum']) ;
net.addLayer([name '_relu'] , ...
dagnn.ReLU(), ...
[name '_sum'], ...
name) ;
lastAdded.var = name ;
end
end
net.addLayer('prediction_avg' , ...
dagnn.Pooling('poolSize', [7 7], 'method', 'avg'), ...
lastAdded.var, ...
'prediction_avg') ;
net.addLayer('prediction' , ...
dagnn.Conv('size', [1 1 2048 1000]), ...
'prediction_avg', ...
'prediction', ...
{'prediction_f', 'prediction_b'}) ;
net.addLayer('loss', ...
dagnn.Loss('loss', 'softmaxlog') ,...
{'prediction', 'label'}, ...
'objective') ;
net.addLayer('top1error', ...
dagnn.Loss('loss', 'classerror'), ...
{'prediction', 'label'}, ...
'top1error') ;
net.addLayer('top5error', ...
dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...
{'prediction', 'label'}, ...
'top5error') ;
% -------------------------------------------------------------------------
% Meta parameters
% -------------------------------------------------------------------------
net.meta.normalization.imageSize = [224 224 3] ;
net.meta.inputSize = [net.meta.normalization.imageSize, 32] ;
net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ;
net.meta.normalization.averageImage = opts.averageImage ;
net.meta.classes.name = opts.classNames ;
net.meta.classes.description = opts.classDescriptions ;
net.meta.augmentation.jitterLocation = true ;
net.meta.augmentation.jitterFlip = true ;
net.meta.augmentation.jitterBrightness = double(0.1 * opts.colorDeviation) ;
net.meta.augmentation.jitterAspect = [3/4, 4/3] ;
net.meta.augmentation.jitterScale = [0.4, 1.1] ;
%net.meta.augmentation.jitterSaturation = 0.4 ;
%net.meta.augmentation.jitterContrast = 0.4 ;
net.meta.inputSize = {'input', [net.meta.normalization.imageSize 32]} ;
%lr = logspace(-1, -3, 60) ;
lr = [0.1 * ones(1,30), 0.01*ones(1,30), 0.001*ones(1,30)] ;
net.meta.trainOpts.learningRate = lr ;
net.meta.trainOpts.numEpochs = numel(lr) ;
net.meta.trainOpts.momentum = 0.9 ;
net.meta.trainOpts.batchSize = 256 ;
net.meta.trainOpts.numSubBatches = 4 ;
net.meta.trainOpts.weightDecay = 0.0001 ;
% Init parameters randomly
net.initParams() ;
% For uniformity with the other ImageNet networks, t
% the input data is *not* normalized to have unit standard deviation,
% whereas this is enforced by batch normalization deeper down.
% The ImageNet standard deviation (for each of R, G, and B) is about 60, so
% we adjust the weights and learing rate accordingly in the first layer.
%
% This simple change improves performance almost +1% top 1 error.
p = net.getParamIndex('conv1_f') ;
net.params(p).value = net.params(p).value / 100 ;
net.params(p).learningRate = net.params(p).learningRate / 100^2 ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, 'dagnn.BatchNorm')
k = net.getParamIndex(net.layers(l).params{3}) ;
net.params(k).learningRate = 0.3 ;
end
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_imagenet_init.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/imagenet/cnn_imagenet_init.m
| 15,279 |
utf_8
|
43bffc7ab4042d49c4f17c0e44c36bf9
|
function net = cnn_imagenet_init(varargin)
% CNN_IMAGENET_INIT Initialize a standard CNN for ImageNet
opts.scale = 1 ;
opts.initBias = 0 ;
opts.weightDecay = 1 ;
%opts.weightInitMethod = 'xavierimproved' ;
opts.weightInitMethod = 'gaussian' ;
opts.model = 'alexnet' ;
opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.averageImage = zeros(3,1) ;
opts.colorDeviation = zeros(3) ;
opts = vl_argparse(opts, varargin) ;
% Define layers
switch opts.model
case 'alexnet'
net.meta.normalization.imageSize = [227, 227, 3] ;
net = alexnet(net, opts) ;
bs = 256 ;
case 'vgg-f'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_f(net, opts) ;
bs = 256 ;
case {'vgg-m', 'vgg-m-1024'}
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_m(net, opts) ;
bs = 196 ;
case 'vgg-s'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_s(net, opts) ;
bs = 128 ;
case 'vgg-vd-16'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_vd(net, opts) ;
bs = 32 ;
case 'vgg-vd-19'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_vd(net, opts) ;
bs = 24 ;
otherwise
error('Unknown model ''%s''', opts.model) ;
end
% final touches
switch lower(opts.weightInitMethod)
case {'xavier', 'xavierimproved'}
net.layers{end}.weights{1} = net.layers{end}.weights{1} / 10 ;
end
net.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;
% Meta parameters
net.meta.inputSize = [net.meta.normalization.imageSize, 32] ;
net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ;
net.meta.normalization.averageImage = opts.averageImage ;
net.meta.classes.name = opts.classNames ;
net.meta.classes.description = opts.classDescriptions;
net.meta.augmentation.jitterLocation = true ;
net.meta.augmentation.jitterFlip = true ;
net.meta.augmentation.jitterBrightness = double(0.1 * opts.colorDeviation) ;
net.meta.augmentation.jitterAspect = [2/3, 3/2] ;
if ~opts.batchNormalization
lr = logspace(-2, -4, 60) ;
else
lr = logspace(-1, -4, 20) ;
end
net.meta.trainOpts.learningRate = lr ;
net.meta.trainOpts.numEpochs = numel(lr) ;
net.meta.trainOpts.batchSize = bs ;
net.meta.trainOpts.weightDecay = 0.0005 ;
% Fill in default values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{'prediction','label'}, 'top1err') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topK',5}), ...
{'prediction','label'}, 'top5err') ;
otherwise
assert(false) ;
end
% --------------------------------------------------------------------
function net = add_block(net, opts, id, h, w, in, out, stride, pad)
% --------------------------------------------------------------------
info = vl_simplenn_display(net) ;
fc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;
if fc
name = 'fc' ;
else
name = 'conv' ;
end
convOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ;
net.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ...
'weights', {{init_weight(opts, h, w, in, out, 'single'), ...
ones(out, 1, 'single')*opts.initBias}}, ...
'stride', stride, ...
'pad', pad, ...
'dilate', 1, ...
'learningRate', [1 2], ...
'weightDecay', [opts.weightDecay 0], ...
'opts', {convOpts}) ;
if opts.batchNormalization
net.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%s',id), ...
'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single'), ...
zeros(out, 2, 'single')}}, ...
'epsilon', 1e-4, ...
'learningRate', [2 1 0.1], ...
'weightDecay', [0 0]) ;
end
net.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%s',id)) ;
% -------------------------------------------------------------------------
function weights = init_weight(opts, h, w, in, out, type)
% -------------------------------------------------------------------------
% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into
% rectifiers: Surpassing human-level performance on imagenet
% classification. CoRR, (arXiv:1502.01852v1), 2015.
switch lower(opts.weightInitMethod)
case 'gaussian'
sc = 0.01/opts.scale ;
weights = randn(h, w, in, out, type)*sc;
case 'xavier'
sc = sqrt(3/(h*w*in)) ;
weights = (rand(h, w, in, out, type)*2 - 1)*sc ;
case 'xavierimproved'
sc = sqrt(2/(h*w*out)) ;
weights = randn(h, w, in, out, type)*sc ;
otherwise
error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;
end
% --------------------------------------------------------------------
function net = add_norm(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'normalize', ...
'name', sprintf('norm%s', id), ...
'param', [5 1 0.0001/5 0.75]) ;
end
% --------------------------------------------------------------------
function net = add_dropout(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'dropout', ...
'name', sprintf('dropout%s', id), ...
'rate', 0.5) ;
end
% --------------------------------------------------------------------
function net = alexnet(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 11, 11, 3, 96, 4, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2', 5, 5, 48, 256, 1, 2) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3', 3, 3, 256, 384, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 192, 384, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 192, 256, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_s(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 3, ...
'pad', [0 2 0 2]) ;
net = add_block(net, opts, '2', 5, 5, 96, 256, 1, 0) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 3, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_m(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2', 5, 5, 96, 256, 2, 1) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
switch opts.model
case 'vgg-m'
bottleneck = 4096 ;
case 'vgg-m-1024'
bottleneck = 1024 ;
end
net = add_block(net, opts, '7', 1, 1, 4096, bottleneck, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, bottleneck, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_f(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 11, 11, 3, 64, 4, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '2', 5, 5, 64, 256, 1, 2) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 256, 256, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_vd(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1_1', 3, 3, 3, 64, 1, 1) ;
net = add_block(net, opts, '1_2', 3, 3, 64, 64, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2_1', 3, 3, 64, 128, 1, 1) ;
net = add_block(net, opts, '2_2', 3, 3, 128, 128, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3_1', 3, 3, 128, 256, 1, 1) ;
net = add_block(net, opts, '3_2', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '3_3', 3, 3, 256, 256, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '3_4', 3, 3, 256, 256, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool3', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '4_1', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4_2', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '4_3', 3, 3, 512, 512, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '4_4', 3, 3, 512, 512, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool4', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '5_1', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5_2', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5_3', 3, 3, 512, 512, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '5_4', 3, 3, 512, 512, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 7, 7, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_imagenet.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/imagenet/cnn_imagenet.m
| 6,211 |
utf_8
|
f11556c91bb9796f533c8f624ad8adbd
|
function [net, info] = cnn_imagenet(varargin)
%CNN_IMAGENET Demonstrates training a CNN on ImageNet
% This demo demonstrates training the AlexNet, VGG-F, VGG-S, VGG-M,
% VGG-VD-16, and VGG-VD-19 architectures on ImageNet data.
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile(vl_rootnn, 'data','ILSVRC2012') ;
opts.modelType = 'alexnet' ;
opts.network = [] ;
opts.networkType = 'simplenn' ;
opts.batchNormalization = true ;
opts.weightInitMethod = 'gaussian' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.modelType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
sfx = [sfx '-' opts.networkType] ;
opts.expDir = fullfile(vl_rootnn, 'data', ['imagenet12-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.numFetchThreads = 12 ;
opts.lite = false ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare data
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
imdb.imageDir = fullfile(opts.dataDir, 'images');
else
imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% Compute image statistics (mean, RGB covariances, etc.)
imageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ;
if exist(imageStatsPath)
load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
else
train = find(imdb.images.set == 1) ;
images = fullfile(imdb.imageDir, imdb.images.name(train(1:100:end))) ;
[averageImage, rgbMean, rgbCovariance] = getImageStats(images, ...
'imageSize', [256 256], ...
'numThreads', opts.numFetchThreads, ...
'gpus', opts.train.gpus) ;
save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
end
[v,d] = eig(rgbCovariance) ;
rgbDeviation = v*sqrt(d) ;
clear v d ;
% -------------------------------------------------------------------------
% Prepare model
% -------------------------------------------------------------------------
if isempty(opts.network)
switch opts.modelType
case 'resnet-50'
net = cnn_imagenet_init_resnet('averageImage', rgbMean, ...
'colorDeviation', rgbDeviation, ...
'classNames', imdb.classes.name, ...
'classDescriptions', imdb.classes.description) ;
opts.networkType = 'dagnn' ;
otherwise
net = cnn_imagenet_init('model', opts.modelType, ...
'batchNormalization', opts.batchNormalization, ...
'weightInitMethod', opts.weightInitMethod, ...
'networkType', opts.networkType, ...
'averageImage', rgbMean, ...
'colorDeviation', rgbDeviation, ...
'classNames', imdb.classes.name, ...
'classDescriptions', imdb.classes.description) ;
end
else
net = opts.network ;
opts.network = [] ;
end
% -------------------------------------------------------------------------
% Learn
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainFn = @cnn_train ;
case 'dagnn', trainFn = @cnn_train_dag ;
end
[net, info] = trainFn(net, imdb, getBatchFn(opts, net.meta), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train) ;
% -------------------------------------------------------------------------
% Deploy
% -------------------------------------------------------------------------
net = cnn_imagenet_deploy(net) ;
modelPath = fullfile(opts.expDir, 'net-deployed.mat')
switch opts.networkType
case 'simplenn'
save(modelPath, '-struct', 'net') ;
case 'dagnn'
net_ = net.saveobj() ;
save(modelPath, '-struct', 'net_') ;
clear net_ ;
end
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', meta.normalization.cropSize, ...
'subtractAverage', mu) ;
% Copy the parameters for data augmentation
bopts.train = bopts.test ;
for f = fieldnames(meta.augmentation)'
f = char(f) ;
bopts.train.(f) = meta.augmentation.(f) ;
end
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if nargout > 0
labels = imdb.images.label(batch) ;
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_imagenet_deploy.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/imagenet/cnn_imagenet_deploy.m
| 6,585 |
utf_8
|
2f3e6d216fa697ff9adfce33e75d44d8
|
function net = cnn_imagenet_deploy(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
net.addLayer('prob', dagnn.SoftMax(), 'prediction', 'prob', {}) ;
else
net.layers{end+1} = struct('name', 'prob', 'type', 'softmax') ;
end
if isDag
dagMergeBatchNorm(net) ;
dagRemoveLayersOfType(net, 'dagnn.BatchNorm') ;
else
net = simpleMergeBatchNorm(net) ;
net = simpleRemoveLayersOfType(net, 'bnorm') ;
end
if ~isDag
net = simpleRemoveMomentum(net) ;
end
% 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 ;
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
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
|
maxkferg/casting-defect-detection-master
|
cnn_imagenet_evaluate.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/imagenet/cnn_imagenet_evaluate.m
| 5,089 |
utf_8
|
f22247bd3614223cad4301daa91f6bd7
|
function info = cnn_imagenet_evaluate(varargin)
% CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile('data', 'ILSVRC2012') ;
opts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;
opts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.networkType = [] ;
opts.lite = false ;
opts.numFetchThreads = 12 ;
opts.train.batchSize = 128 ;
opts.train.numEpochs = 1 ;
opts.train.gpus = [] ;
opts.train.prefetch = true ;
opts.train.expDir = opts.expDir ;
opts = vl_argparse(opts, varargin) ;
display(opts);
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
imdb.imageDir = fullfile(opts.dataDir, 'images');
else
imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = load(opts.modelPath) ;
if isfield(net, 'net') ;
net = net.net ;
end
% Cannot use isa('dagnn.DagNN') because it is not an object yet
isDag = isfield(net, 'params') ;
if isDag
opts.networkType = 'dagnn' ;
net = dagnn.DagNN.loadobj(net) ;
trainfn = @cnn_train_dag ;
% Drop existing loss layers
drop = arrayfun(@(x) isa(x.block,'dagnn.Loss'), net.layers) ;
for n = {net.layers(drop).name}
net.removeLayer(n) ;
end
% Extract raw predictions from softmax
sftmx = arrayfun(@(x) isa(x.block,'dagnn.SoftMax'), net.layers) ;
predVar = 'prediction' ;
for n = {net.layers(sftmx).name}
% check if output
l = net.getLayerIndex(n) ;
v = net.getVarIndex(net.layers(l).outputs{1}) ;
if net.vars(v).fanout == 0
% remove this layer and update prediction variable
predVar = net.layers(l).inputs{1} ;
net.removeLayer(n) ;
end
end
% Add custom objective and loss layers on top of raw predictions
net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), ...
{predVar,'label'}, 'objective') ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{predVar,'label'}, 'top1err') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topK',5}), ...
{predVar,'label'}, 'top5err') ;
% Make sure that the input is called 'input'
v = net.getVarIndex('data') ;
if ~isnan(v)
net.renameVar('data', 'input') ;
end
% Swtich to test mode
net.mode = 'test' ;
else
opts.networkType = 'simplenn' ;
net = vl_simplenn_tidy(net) ;
trainfn = @cnn_train ;
net.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss
end
% Synchronize label indexes used in IMDB with the ones used in NET
imdb = cnn_imagenet_sync_labels(imdb, net);
% Run evaluation
[net, info] = trainfn(net, imdb, getBatchFn(opts, net.meta), ...
opts.train, ...
'train', NaN, ...
'val', find(imdb.images.set==2)) ;
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if isfield(meta.normalization, 'keepAspect')
keepAspect = meta.normalization.keepAspect ;
else
keepAspect = true ;
end
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', max(meta.normalization.imageSize(1:2)) / 256, ...
'subtractAverage', mu, ...
'keepAspect', keepAspect) ;
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if nargout > 0
labels = imdb.images.label(batch) ;
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_mnist_init.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/mnist/cnn_mnist_init.m
| 3,156 |
utf_8
|
6e6819c9281561e385955ece4ec7a1a4
|
function net = cnn_mnist_init(varargin)
% CNN_MNIST_LENET Initialize a CNN similar for MNIST
opts.batchNormalization = true ;
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;
rng('default');
rng(0) ;
f=1/100 ;
net.layers = {} ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,1,20, 'single'), zeros(1, 20, 'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,20,50, 'single'),zeros(1,50,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(4,4,50,500, 'single'), zeros(1,500,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu') ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(1,1,500,10, 'single'), zeros(1,10,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'softmaxloss') ;
% optionally switch to batch normalization
if opts.batchNormalization
net = insertBnorm(net, 1) ;
net = insertBnorm(net, 4) ;
net = insertBnorm(net, 7) ;
end
% Meta parameters
net.meta.inputSize = [28 28 1] ;
net.meta.trainOpts.learningRate = 0.001 ;
net.meta.trainOpts.numEpochs = 20 ;
net.meta.trainOpts.batchSize = 100 ;
% Fill in defaul values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{'prediction', 'label'}, 'error') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topk', 5}), {'prediction', 'label'}, 'top5err') ;
otherwise
assert(false) ;
end
% --------------------------------------------------------------------
function net = insertBnorm(net, l)
% --------------------------------------------------------------------
assert(isfield(net.layers{l}, 'weights'));
ndim = size(net.layers{l}.weights{1}, 4);
layer = struct('type', 'bnorm', ...
'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...
'learningRate', [1 1 0.05], ...
'weightDecay', [0 0]) ;
net.layers{l}.weights{2} = [] ; % eliminate bias in previous conv layer
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_mnist.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/mnist/cnn_mnist.m
| 4,613 |
utf_8
|
d23586e79502282a6f6d632c3cf8a47e
|
function [net, info] = cnn_mnist(varargin)
%CNN_MNIST Demonstrates MatConvNet on MNIST
run(fullfile(fileparts(mfilename('fullpath')),...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.batchNormalization = false ;
opts.network = [] ;
opts.networkType = 'simplenn' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.networkType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
opts.expDir = fullfile(vl_rootnn, 'data', ['mnist-baseline-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile(vl_rootnn, 'data', 'mnist') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% --------------------------------------------------------------------
% Prepare data
% --------------------------------------------------------------------
if isempty(opts.network)
net = cnn_mnist_init('batchNormalization', opts.batchNormalization, ...
'networkType', opts.networkType) ;
else
net = opts.network ;
opts.network = [] ;
end
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getMnistImdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainfn = @cnn_train ;
case 'dagnn', trainfn = @cnn_train_dag ;
end
[net, info] = trainfn(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
% --------------------------------------------------------------------
function fn = getBatch(opts)
% --------------------------------------------------------------------
switch lower(opts.networkType)
case 'simplenn'
fn = @(x,y) getSimpleNNBatch(x,y) ;
case 'dagnn'
bopts = struct('numGpus', numel(opts.train.gpus)) ;
fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end
% --------------------------------------------------------------------
function [images, labels] = getSimpleNNBatch(imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
% --------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if opts.numGpus > 0
images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;
% --------------------------------------------------------------------
function imdb = getMnistImdb(opts)
% --------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
files = {'train-images-idx3-ubyte', ...
'train-labels-idx1-ubyte', ...
't10k-images-idx3-ubyte', ...
't10k-labels-idx1-ubyte'} ;
if ~exist(opts.dataDir, 'dir')
mkdir(opts.dataDir) ;
end
for i=1:4
if ~exist(fullfile(opts.dataDir, files{i}), 'file')
url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ;
fprintf('downloading %s\n', url) ;
gunzip(url, opts.dataDir) ;
end
end
f=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ;
x1=fread(f,inf,'uint8');
fclose(f) ;
x1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ;
f=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ;
x2=fread(f,inf,'uint8');
fclose(f) ;
x2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ;
f=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ;
y1=fread(f,inf,'uint8');
fclose(f) ;
y1=double(y1(9:end)')+1 ;
f=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ;
y2=fread(f,inf,'uint8');
fclose(f) ;
y2=double(y2(9:end)')+1 ;
set = [ones(1,numel(y1)) 3*ones(1,numel(y2))];
data = single(reshape(cat(3, x1, x2),28,28,1,[]));
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean) ;
imdb.images.data = data ;
imdb.images.data_mean = dataMean;
imdb.images.labels = cat(2, y1, y2) ;
imdb.images.set = set ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
|
github
|
maxkferg/casting-defect-detection-master
|
cnn_toy_data.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/examples/custom_imdb/cnn_toy_data.m
| 5,535 |
utf_8
|
eb12be3c467c548d0480c46c818e05cd
|
function [net, stats] = cnn_toy_data(varargin)
% CNN_TOY_DATA
% Minimal demonstration of MatConNet training of a CNN on toy data.
%
% It also serves as a short tutorial on creating and using a custom imdb
% (image database).
%
% The task is to distinguish between images of triangles, squares and
% circles.
% Copyright (C) 2017 Joao F. Henriques.
% 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).
run([fileparts(mfilename('fullpath')) '/../../matlab/vl_setupnn.m']) ;
% Parameter defaults. You can add any custom parameters here (e.g.
% opts.alpha = 1), and change them when calling: cnn_toy_data('alpha', 2).
opts.train.batchSize = 200 ;
opts.train.numEpochs = 10 ;
opts.train.continue = true ;
opts.train.gpus = [] ;
opts.train.learningRate = 0.01 ;
opts.train.expDir = [vl_rootnn '/data/toy'] ;
opts.dataDir = [vl_rootnn '/data/toy-dataset'] ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = [opts.train.expDir '/imdb.mat'] ;
opts = vl_argparse(opts, varargin) ;
% --------------------------------------------------------------------
% Prepare data
% --------------------------------------------------------------------
% Generate images if they don't exist (this would be skipped for real data)
if ~exist(opts.dataDir, 'dir')
mkdir(opts.dataDir) ;
cnn_toy_data_generator(opts.dataDir) ;
end
% Create image database (imdb struct). It can be cached to a file for speed
if exist(opts.imdbPath, 'file')
disp('Reloading image database...')
imdb = load(opts.imdbPath) ;
else
disp('Creating image database...')
imdb = getImdb(opts.dataDir) ;
mkdir(fileparts(opts.imdbPath)) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% Create network (see HELP VL_SIMPLENN)
f = 1/100 ;
net.layers = {} ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,1,5, 'single'), zeros(1, 5, 'single')}}) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,5,10, 'single'),zeros(1,10,'single')}}) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,10,3, 'single'), zeros(1,3,'single')}}) ;
net.layers{end+1} = struct('type', 'softmaxloss') ;
% Fill in any values we didn't specify explicitly
net = vl_simplenn_tidy(net) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
use_gpu = ~isempty(opts.train.gpus) ;
% Start training
[net, stats] = cnn_train(net, imdb, @(imdb, batch) getBatch(imdb, batch, use_gpu), ...
'train', find(imdb.set == 1), 'val', find(imdb.set == 2), opts.train) ;
% Visualize the learned filters
figure(3) ; vl_tshow(net.layers{1}.weights{1}) ; title('Conv1 filters') ;
figure(4) ; vl_tshow(net.layers{3}.weights{1}) ; title('Conv2 filters') ;
figure(5) ; vl_tshow(net.layers{5}.weights{1}) ; title('Conv3 filters') ;
% --------------------------------------------------------------------
function [images, labels] = getBatch(imdb, batch, use_gpu)
% --------------------------------------------------------------------
% This is where we return a given set of images (and their labels) from
% our imdb structure.
% If the dataset was too large to fit in memory, getBatch could load images
% from disk instead (with indexes given in 'batch').
images = imdb.images(:,:,:,batch) ;
labels = imdb.labels(batch) ;
if use_gpu
images = gpuArray(images) ;
end
% --------------------------------------------------------------------
function imdb = getImdb(dataDir)
% --------------------------------------------------------------------
% Initialize the imdb structure (image database).
% Note the fields are arbitrary: only your getBatch needs to understand it.
% The field imdb.set is used to distinguish between the training and
% validation sets, and is only used in the above call to cnn_train.
% The sets, and number of samples per label in each set
sets = {'train', 'val'} ;
numSamples = [1500, 150] ;
% Preallocate memory
totalSamples = 4950 ; % 3 * 1500 + 3 * 150
images = zeros(32, 32, 1, totalSamples, 'single') ;
labels = zeros(totalSamples, 1) ;
set = ones(totalSamples, 1) ;
% Read all samples
sample = 1 ;
for s = 1:2 % Iterate sets
for label = 1:3 % Iterate labels
for i = 1:numSamples(s) % Iterate samples
% Read image
im = imread(sprintf('%s/%s/%i/%04i.png', dataDir, sets{s}, label, i)) ;
% Store it, along with label and train/val set information
images(:,:,:,sample) = single(im) ;
labels(sample) = label ;
set(sample) = s ;
sample = sample + 1 ;
end
end
end
% Show some random example images
figure(2) ;
montage(images(:,:,:,randperm(totalSamples, 100))) ;
title('Example images') ;
% Remove mean over whole dataset
images = bsxfun(@minus, images, mean(images, 4)) ;
% Store results in the imdb struct
imdb.images = images ;
imdb.labels = labels ;
imdb.set = set ;
|
github
|
maxkferg/casting-defect-detection-master
|
vl_nnloss.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/vl_nnloss.m
| 11,336 |
utf_8
|
e33da54333122fdd2f1a017a29e4f586
|
function y = vl_nnloss(x,c,varargin)
%VL_NNLOSS CNN categorical or attribute loss.
% Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction
% scores X given the categorical labels C.
%
% The prediction scores X are organised as a field of prediction
% vectors, represented by a H x W x D x N array. The first two
% dimensions, H and W, are spatial and correspond to the height and
% width of the field; the third dimension D is the number of
% categories or classes; finally, the dimension N is the number of
% data items (images) packed in the array.
%
% While often one has H = W = 1, the case W, H > 1 is useful in
% dense labelling problems such as image segmentation. In the latter
% case, the loss is summed across pixels (contributions can be
% weighed using the `InstanceWeights` option described below).
%
% The array C contains the categorical labels. In the simplest case,
% C is an array of integers in the range [1, D] with N elements
% specifying one label for each of the N images. If H, W > 1, the
% same label is implicitly applied to all spatial locations.
%
% In the second form, C has dimension H x W x 1 x N and specifies a
% categorical label for each spatial location.
%
% In the third form, C has dimension H x W x D x N and specifies
% attributes rather than categories. Here elements in C are either
% +1 or -1 and C, where +1 denotes that an attribute is present and
% -1 that it is not. The key difference is that multiple attributes
% can be active at the same time, while categories are mutually
% exclusive. By default, the loss is *summed* across attributes
% (unless otherwise specified using the `InstanceWeights` option
% described below).
%
% DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block
% projected onto the output derivative DZDY. DZDX and DZDY have the
% same dimensions as X and Y respectively.
%
% VL_NNLOSS() supports several loss functions, which can be selected
% by using the option `type` described below. When each scalar c in
% C is interpreted as a categorical label (first two forms above),
% the following losses can be used:
%
% Classification error:: `classerror`
% L(X,c) = (argmax_q X(q) ~= c). Note that the classification
% error derivative is flat; therefore this loss is useful for
% assessment, but not for training a model.
%
% Top-K classification error:: `topkerror`
% L(X,c) = (rank X(c) in X <= K). The top rank is the one with
% highest score. For K=1, this is the same as the
% classification error. K is controlled by the `topK` option.
%
% Log loss:: `log`
% L(X,c) = - log(X(c)). This function assumes that X(c) is the
% predicted probability of class c (hence the vector X must be non
% negative and sum to one).
%
% Softmax log loss (multinomial logistic loss):: `softmaxlog`
% L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)).
% This is the same as the `log` loss, but renormalizes the
% predictions using the softmax function.
%
% Multiclass hinge loss:: `mhinge`
% L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is
% the score margin for class c against the other classes. See
% also the `mmhinge` loss below.
%
% Multiclass structured hinge loss:: `mshinge`
% L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c}
% X(q). This is the same as the `mhinge` loss, but computes the
% margin between the prediction scores first. This is also known
% the Crammer-Singer loss, an example of a structured prediction
% loss.
%
% When C is a vector of binary attribures c in (+1,-1), each scalar
% prediction score x is interpreted as voting for the presence or
% absence of a particular attribute. The following losses can be
% used:
%
% Binary classification error:: `binaryerror`
% L(x,c) = (sign(x - t) ~= c). t is a threshold that can be
% specified using the `threshold` option and defaults to zero. If
% x is a probability, it should be set to 0.5.
%
% Binary log loss:: `binarylog`
% L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the
% probability that the attribute is active (c=+1). Hence x must be
% a number in the range [0,1]. This is the binary version of the
% `log` loss.
%
% Logistic log loss:: `logistic`
% L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog`
% loss, but implicitly normalizes the score x into a probability
% using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 +
% exp(-x)). This is also equivalent to `softmaxlog` loss where
% class c=+1 is assigned score x and class c=-1 is assigned score
% 0.
%
% Hinge loss:: `hinge`
% L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for
% binary classification. This is equivalent to the `mshinge` loss
% if class c=+1 is assigned score x and class c=-1 is assigned
% score 0.
%
% VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals
% options:
%
% InstanceWeights:: []
% Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is
% a per-instance weight extracted from the array
% `InstanceWeights`. For categorical losses, this is either a H x
% W x 1 or a H x W x 1 x N array. For attribute losses, this is
% either a H x W x D or a H x W x D x N array.
%
% TopK:: 5
% Top-K value for the top-K error. Note that K should not
% exceed the number of labels.
%
% See also: VL_NNSOFTMAX().
% Copyright (C) 2014-15 Andrea Vedaldi.
% Copyright (C) 2016 Karel Lenc.
% 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 ~isempty(varargin) && ~ischar(varargin{1}) % passed in dzdy
dzdy = varargin{1} ;
varargin(1) = [] ;
else
dzdy = [] ;
end
opts.instanceWeights = [] ;
opts.classWeights = [] ;
opts.threshold = 0 ;
opts.loss = 'softmaxlog' ;
opts.topK = 5 ;
opts = vl_argparse(opts, varargin, 'nonrecursive') ;
inputSize = [size(x,1) size(x,2) size(x,3) size(x,4)] ;
% Form 1: C has one label per image. In this case, get C in form 2 or
% form 3.
c = gather(c) ;
if numel(c) == inputSize(4)
c = reshape(c, [1 1 1 inputSize(4)]) ;
c = repmat(c, inputSize(1:2)) ;
end
hasIgnoreLabel = any(c(:) == 0);
% --------------------------------------------------------------------
% Spatial weighting
% --------------------------------------------------------------------
% work around a bug in MATLAB, where native cast() would slow
% progressively
if isa(x, 'gpuArray')
switch classUnderlying(x) ;
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
else
switch class(x)
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
end
labelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ;
assert(isequal(labelSize(1:2), inputSize(1:2))) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = [] ;
switch lower(opts.loss)
case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'}
% there must be one categorical label per prediction vector
assert(labelSize(3) == 1) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c(:,:,1,:) ~= 0) ;
end
case {'binaryerror', 'binarylog', 'logistic', 'hinge'}
% there must be one categorical label per prediction scalar
assert(labelSize(3) == inputSize(3)) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c ~= 0) ;
end
otherwise
error('Unknown loss ''%s''.', opts.loss) ;
end
if ~isempty(opts.instanceWeights)
% important: this code needs to broadcast opts.instanceWeights to
% an array of the same size as c
if isempty(instanceWeights)
instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ;
else
instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights);
end
end
% --------------------------------------------------------------------
% Do the work
% --------------------------------------------------------------------
switch lower(opts.loss)
case {'log', 'softmaxlog', 'mhinge', 'mshinge'}
% from category labels to indexes
numPixelsPerImage = prod(inputSize(1:2)) ;
numPixels = numPixelsPerImage * inputSize(4) ;
imageVolume = numPixelsPerImage * inputSize(3) ;
n = reshape(0:numPixels-1,labelSize) ;
offset = 1 + mod(n, numPixelsPerImage) + ...
imageVolume * fix(n / numPixelsPerImage) ;
ci = offset + numPixelsPerImage * max(c - 1,0) ;
end
if nargin <= 2 || isempty(dzdy)
switch lower(opts.loss)
case 'classerror'
[~,chat] = max(x,[],3) ;
t = cast(c ~= chat) ;
case 'topkerror'
[~,predictions] = sort(x,3,'descend') ;
t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ;
case 'log'
t = - log(x(ci)) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
t = Xmax + log(sum(ex,3)) - x(ci) ;
case 'mhinge'
t = max(0, 1 - x(ci)) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
t = max(0, 1 - x(ci) + max(Q,[],3)) ;
case 'binaryerror'
t = cast(sign(x - opts.threshold) ~= c) ;
case 'binarylog'
t = -log(c.*(x-0.5) + 0.5) ;
case 'logistic'
%t = log(1 + exp(-c.*X)) ;
a = -c.*x ;
b = max(0, a) ;
t = b + log(exp(-b) + exp(a-b)) ;
case 'hinge'
t = max(0, 1 - c.*x) ;
end
if ~isempty(instanceWeights)
y = instanceWeights(:)' * t(:) ;
else
y = sum(t(:));
end
else
if ~isempty(instanceWeights)
dzdy = dzdy * instanceWeights ;
end
switch lower(opts.loss)
case {'classerror', 'topkerror'}
y = zerosLike(x) ;
case 'log'
y = zerosLike(x) ;
y(ci) = - dzdy ./ max(x(ci), 1e-8) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
y = bsxfun(@rdivide, ex, sum(ex,3)) ;
y(ci) = y(ci) - 1 ;
y = bsxfun(@times, dzdy, y) ;
case 'mhinge'
y = zerosLike(x) ;
y(ci) = - dzdy .* (x(ci) < 1) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
[~, q] = max(Q,[],3) ;
qi = offset + numPixelsPerImage * (q - 1) ;
W = dzdy .* (x(ci) - x(qi) < 1) ;
y = zerosLike(x) ;
y(ci) = - W ;
y(qi) = + W ;
case 'binaryerror'
y = zerosLike(x) ;
case 'binarylog'
y = - dzdy ./ (x + (c-1)*0.5) ;
case 'logistic'
% t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y)
% t = 1 / (1 + exp(Y.*X)) .* (-Y)
y = - dzdy .* c ./ (1 + exp(c.*x)) ;
case 'hinge'
y = - dzdy .* c .* (c.*x < 1) ;
end
end
% --------------------------------------------------------------------
function y = zerosLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.zeros(size(x),classUnderlying(x)) ;
else
y = zeros(size(x),'like',x) ;
end
% --------------------------------------------------------------------
function y = onesLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.ones(size(x),classUnderlying(x)) ;
else
y = ones(size(x),'like',x) ;
end
|
github
|
maxkferg/casting-defect-detection-master
|
vl_compilenn.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/vl_compilenn.m
| 30,050 |
utf_8
|
6339b625106e6c7b479e57c2b9aa578e
|
function vl_compilenn(varargin)
%VL_COMPILENN Compile the MatConvNet toolbox.
% The `vl_compilenn()` function compiles the MEX files in the
% MatConvNet toolbox. See below for the requirements for compiling
% CPU and GPU code, respectively.
%
% `vl_compilenn('OPTION', ARG, ...)` accepts the following options:
%
% `EnableGpu`:: `false`
% Set to true in order to enable GPU support.
%
% `Verbose`:: 0
% Set the verbosity level (0, 1 or 2).
%
% `Debug`:: `false`
% Set to true to compile the binaries with debugging
% information.
%
% `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc`
% Choose the method used to compile the CUDA code. There are two
% methods:
%
% * The **`mex`** method uses the MATLAB MEX command with the
% configuration file
% `<MatConvNet>/matlab/src/config/mex_CUDA_<arch>.[sh/xml]`
% This configuration file is in XML format since MATLAB 8.3
% (R2014a) and is a Shell script for earlier versions. This
% is, principle, the preferred method as it uses the
% MATLAB-sanctioned compiler options.
%
% * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc`
% directly to compile CUDA source code into object files.
%
% This method allows to use a CUDA toolkit version that is not
% the one that officially supported by a particular MATALB
% version (see below). It is also the default method for
% compilation under Windows and with CuDNN.
%
% `CudaRoot`:: guessed automatically
% This option specifies the path to the CUDA toolkit to use for
% compilation.
%
% `EnableImreadJpeg`:: `true`
% Set this option to `true` to compile `vl_imreadjpeg`.
%
% `EnableDouble`:: `true`
% Set this option to `true` to compile the support for DOUBLE
% data types.
%
% `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac)
% The image library to use for `vl_impreadjpeg`.
%
% `ImageLibraryCompileFlags`:: platform dependent
% A cell-array of additional flags to use when compiling
% `vl_imreadjpeg`.
%
% `ImageLibraryLinkFlags`:: platform dependent
% A cell-array of additional flags to use when linking
% `vl_imreadjpeg`.
%
% `EnableCudnn`:: `false`
% Set to `true` to compile CuDNN support. See CuDNN
% documentation for the Hardware/CUDA version requirements.
%
% `CudnnRoot`:: `'local/'`
% Directory containing the unpacked binaries and header files of
% the CuDNN library.
%
% ## Compiling the CPU code
%
% By default, the `EnableGpu` option is switched to off, such that
% the GPU code support is not compiled in.
%
% Generally, you only need a 64bit C/C++ compiler (usually Xcode, GCC or
% Visual Studio for Mac, Linux, and Windows respectively). The
% compiler can be setup in MATLAB using the
%
% mex -setup
%
% command.
%
% ## Compiling the GPU code
%
% In order to compile the GPU code, set the `EnableGpu` option to
% `true`. For this to work you will need:
%
% * To satisfy all the requirements to compile the CPU code (see
% above).
%
% * A NVIDIA GPU with at least *compute capability 2.0*.
%
% * The *MATALB Parallel Computing Toolbox*. This can be purchased
% from Mathworks (type `ver` in MATLAB to see if this toolbox is
% already comprised in your MATLAB installation; it often is).
%
% * A copy of the *CUDA Devkit*, which can be downloaded for free
% from NVIDIA. Note that each MATLAB version requires a
% particular CUDA Devkit version:
%
% | MATLAB version | Release | CUDA Devkit |
% |----------------|---------|--------------|
% | 8.2 | 2013b | 5.5 |
% | 8.3 | 2014a | 5.5 |
% | 8.4 | 2014b | 6.0 |
% | 8.6 | 2015b | 7.0 |
% | 9.0 | 2016a | 7.5 |
%
% Different versions of CUDA may work using the hack described
% above (i.e. setting the `CudaMethod` to `nvcc`).
%
% The following configurations have been tested successfully:
%
% * Windows 7 x64, MATLAB R2014a, Visual C++ 2010, 2013 and CUDA Toolkit
% 6.5. VS 2015 CPU version only (not supported by CUDA Toolkit yet).
% * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA
% Toolkit 6.5.
% * Mac OS X 10.9, 10.10, 10.11, MATLAB R2013a to R2016a, Xcode, CUDA
% Toolkit 5.5 to 7.5.
% * GNU/Linux, MATALB R2014a/R2015a/R2015b/R2016a, gcc/g++, CUDA Toolkit 5.5/6.5/7.5.
%
% Compilation on Windows with MinGW compiler (the default mex compiler in
% Matlab) is not supported. For Windows, please reconfigure mex to use
% Visual Studio C/C++ compiler.
% Furthermore your GPU card must have ComputeCapability >= 2.0 (see
% output of `gpuDevice()`) in order to be able to run the GPU code.
% To change the compute capabilities, for `mex` `CudaMethod` edit
% the particular config file. For the 'nvcc' method, compute
% capability is guessed based on the GPUDEVICE output. You can
% override it by setting the 'CudaArch' parameter (e.g. in case of
% multiple GPUs with various architectures).
%
% See also: [Compliling MatConvNet](../install.md#compiling),
% [Compiling MEX files containing CUDA
% code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html),
% `vl_setup()`, `vl_imreadjpeg()`.
% Copyright (C) 2014-16 Karel Lenc and 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).
% Get MatConvNet root directory
root = fileparts(fileparts(mfilename('fullpath'))) ;
addpath(fullfile(root, 'matlab')) ;
% --------------------------------------------------------------------
% Parse options
% --------------------------------------------------------------------
opts.enableGpu = false;
opts.enableImreadJpeg = true;
opts.enableCudnn = false;
opts.enableDouble = true;
opts.imageLibrary = [] ;
opts.imageLibraryCompileFlags = {} ;
opts.imageLibraryLinkFlags = [] ;
opts.verbose = 0;
opts.debug = false;
opts.cudaMethod = [] ;
opts.cudaRoot = [] ;
opts.cudaArch = [] ;
opts.defCudaArch = [...
'-gencode=arch=compute_20,code=\"sm_20,compute_20\" '...
'-gencode=arch=compute_30,code=\"sm_30,compute_30\"'];
opts.cudnnRoot = 'local/cudnn' ;
opts = vl_argparse(opts, varargin);
% --------------------------------------------------------------------
% Files to compile
% --------------------------------------------------------------------
arch = computer('arch') ;
if isempty(opts.imageLibrary)
switch arch
case 'glnxa64', opts.imageLibrary = 'libjpeg' ;
case 'maci64', opts.imageLibrary = 'quartz' ;
case 'win64', opts.imageLibrary = 'gdiplus' ;
end
end
if isempty(opts.imageLibraryLinkFlags)
switch opts.imageLibrary
case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ;
case 'quartz', opts.imageLibraryLinkFlags = {'-framework Cocoa -framework ImageIO'} ;
case 'gdiplus', opts.imageLibraryLinkFlags = {'gdiplus.lib'} ;
end
end
lib_src = {} ;
mex_src = {} ;
% Files that are compiled as CPP or CU depending on whether GPU support
% is enabled.
if opts.enableGpu, ext = 'cu' ; else ext='cpp' ; end
lib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbnorm.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbilinearsampler.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnroipooling.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbnorm.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbilinearsampler.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnroipool.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_taccummex.' ext]) ;
switch arch
case {'glnxa64','maci64'}
% not yet supported in windows
mex_src{end+1} = fullfile(root,'matlab','src',['vl_tmove.' ext]) ;
end
% CPU-specific files
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','imread.cpp') ;
% GPU-specific files
if opts.enableGpu
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ;
mex_src{end+1} = fullfile(root,'matlab','src','vl_cudatool.cu') ;
end
% cuDNN-specific files
if opts.enableCudnn
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbilinearsampler_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbnorm_cudnn.cu') ;
end
% Other files
if opts.enableImreadJpeg
mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg_old.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ;
end
% --------------------------------------------------------------------
% Setup CUDA toolkit
% --------------------------------------------------------------------
if opts.enableGpu
opts.verbose && fprintf('%s: * CUDA configuration *\n', mfilename) ;
% Find the CUDA Devkit
if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts) ; end
opts.verbose && fprintf('%s:\tCUDA: using CUDA Devkit ''%s''.\n', ...
mfilename, opts.cudaRoot) ;
opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ;
switch arch
case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ;
case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ;
case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ;
otherwise, error('Unsupported architecture ''%s''.', arch) ;
end
% Set the nvcc method as default for Win platforms
if strcmp(arch, 'win64') && isempty(opts.cudaMethod)
opts.cudaMethod = 'nvcc';
end
% Activate the CUDA Devkit
cuver = activate_nvcc(opts.nvccPath) ;
opts.verbose && fprintf('%s:\tCUDA: using NVCC ''%s'' (%d).\n', ...
mfilename, opts.nvccPath, cuver) ;
% Set the CUDA arch string (select GPU architecture)
if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end
opts.verbose && fprintf('%s:\tCUDA: NVCC architecture string: ''%s''.\n', ...
mfilename, opts.cudaArch) ;
end
if opts.enableCudnn
opts.cudnnIncludeDir = fullfile(opts.cudnnRoot, 'include') ;
switch arch
case 'win64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib', 'x64') ;
case 'maci64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib') ;
case 'glnxa64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib64') ;
otherwise, error('Unsupported architecture ''%s''.', arch) ;
end
end
% --------------------------------------------------------------------
% Compiler options
% --------------------------------------------------------------------
% Build directories
mex_dir = fullfile(root, 'matlab', 'mex') ;
bld_dir = fullfile(mex_dir, '.build');
if ~exist(fullfile(bld_dir,'bits','impl'), 'dir')
mkdir(fullfile(bld_dir,'bits','impl')) ;
end
% Compiler flags
flags.cc = {} ;
flags.ccpass = {} ;
flags.ccoptim = {} ;
flags.link = {} ;
flags.linklibs = {} ;
flags.linkpass = {} ;
flags.nvccpass = {char(opts.cudaArch)} ;
if opts.verbose > 1
flags.cc{end+1} = '-v' ;
end
if opts.debug
flags.cc{end+1} = '-g' ;
flags.nvccpass{end+1} = '-O0' ;
else
flags.cc{end+1} = '-DNDEBUG' ;
flags.nvccpass{end+1} = '-O3' ;
end
if opts.enableGpu
flags.cc{end+1} = '-DENABLE_GPU' ;
end
if opts.enableCudnn
flags.cc{end+1} = '-DENABLE_CUDNN' ;
flags.cc{end+1} = ['-I"' opts.cudnnIncludeDir '"'] ;
end
if opts.enableDouble
flags.cc{end+1} = '-DENABLE_DOUBLE' ;
end
flags.link{end+1} = '-lmwblas' ;
switch arch
case {'maci64'}
case {'glnxa64'}
flags.linklibs{end+1} = '-lrt' ;
case {'win64'}
% VisualC does not pass this even if available in the CPU architecture
flags.cc{end+1} = '-D__SSSE3__' ;
end
if opts.enableImreadJpeg
flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ;
flags.linklibs = horzcat(flags.linklibs, opts.imageLibraryLinkFlags) ;
end
if opts.enableGpu
flags.link = horzcat(flags.link, {['-L"' opts.cudaLibDir '"'], '-lcudart', '-lcublas'}) ;
switch arch
case {'maci64', 'glnxa64'}
flags.link{end+1} = '-lmwgpu' ;
case 'win64'
flags.link{end+1} = '-lgpu' ;
end
if opts.enableCudnn
flags.link{end+1} = ['-L"' opts.cudnnLibDir '"'] ;
flags.link{end+1} = '-lcudnn' ;
end
end
switch arch
case {'maci64'}
flags.ccpass{end+1} = '-mmacosx-version-min=10.9' ;
flags.linkpass{end+1} = '-mmacosx-version-min=10.9' ;
flags.ccoptim{end+1} = '-mssse3 -ffast-math' ;
flags.nvccpass{end+1} = '-Xcompiler -fPIC' ;
if opts.enableGpu
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ;
end
if opts.enableGpu && opts.enableCudnn
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ;
end
if opts.enableGpu && cuver < 70000
% CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native
% clang libc++. This should go away in the future.
flags.ccpass{end+1} = '-stdlib=libstdc++' ;
flags.linkpass{end+1} = '-stdlib=libstdc++' ;
if ~verLessThan('matlab', '8.5.0')
% Complicating matters, MATLAB 8.5.0 links to clang's libc++ by
% default when linking MEX files overriding the option above. We
% force it to use GCC libstdc++
flags.linkpass{end+1} = '-L"$MATLABROOT/bin/maci64" -lmx -lmex -lmat -lstdc++' ;
end
end
case {'glnxa64'}
flags.ccoptim{end+1} = '-mssse3 -ftree-vect-loop-version -ffast-math -funroll-all-loops' ;
flags.nvccpass{end+1} = '-Xcompiler -fPIC -D_FORCE_INLINES' ;
if opts.enableGpu
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ;
end
if opts.enableGpu && opts.enableCudnn
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ;
end
case {'win64'}
flags.nvccpass{end+1} = '-Xcompiler /MD' ;
cl_path = fileparts(check_clpath()); % check whether cl.exe in path
flags.nvccpass{end+1} = sprintf('--compiler-bindir "%s"', cl_path) ;
end
% --------------------------------------------------------------------
% Command flags
% --------------------------------------------------------------------
flags.mexcc = horzcat(flags.cc, ...
{'-largeArrayDims'}, ...
{['CXXFLAGS=$CXXFLAGS ' strjoin(flags.ccpass)]}, ...
{['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' strjoin(flags.ccoptim)]}) ;
if ~ispc, flags.mexcc{end+1} = '-cxx'; end
% mex: compile GPU
flags.mexcu= horzcat({'-f' mex_cuda_config(root)}, ...
flags.cc, ...
{'-largeArrayDims'}, ...
{['CXXFLAGS=$CXXFLAGS ' quote_nvcc(flags.ccpass) ' ' strjoin(flags.nvccpass)]}, ...
{['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' quote_nvcc(flags.ccoptim)]}) ;
% mex: link
flags.mexlink = horzcat(flags.cc, flags.link, ...
{'-largeArrayDims'}, ...
{['LDFLAGS=$LDFLAGS ', strjoin(flags.linkpass)]}, ...
{['LINKLIBS=', strjoin(flags.linklibs), ' $LINKLIBS']}) ;
% nvcc: compile GPU
flags.nvcc = horzcat(flags.cc, ...
{opts.cudaArch}, ...
{sprintf('-I"%s"', fullfile(matlabroot, 'extern', 'include'))}, ...
{sprintf('-I"%s"', fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include'))}, ...
{quote_nvcc(flags.ccpass)}, ...
{quote_nvcc(flags.ccoptim)}, ...
flags.nvccpass) ;
if opts.verbose
fprintf('%s: * Compiler and linker configurations *\n', mfilename) ;
fprintf('%s: \tintermediate build products directory: %s\n', mfilename, bld_dir) ;
fprintf('%s: \tMEX files: %s/\n', mfilename, mex_dir) ;
fprintf('%s: \tMEX options [CC CPU]: %s\n', mfilename, strjoin(flags.mexcc)) ;
fprintf('%s: \tMEX options [LINK]: %s\n', mfilename, strjoin(flags.mexlink)) ;
end
if opts.verbose && opts.enableGpu
fprintf('%s: \tMEX options [CC GPU]: %s\n', mfilename, strjoin(flags.mexcu)) ;
end
if opts.verbose && opts.enableGpu && strcmp(opts.cudaMethod,'nvcc')
fprintf('%s: \tNVCC options [CC GPU]: %s\n', mfilename, strjoin(flags.nvcc)) ;
end
if opts.verbose && opts.enableImreadJpeg
fprintf('%s: * Reading images *\n', mfilename) ;
fprintf('%s: \tvl_imreadjpeg enabled\n', mfilename) ;
fprintf('%s: \timage library: %s\n', mfilename, opts.imageLibrary) ;
fprintf('%s: \timage library compile flags: %s\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ;
fprintf('%s: \timage library link flags: %s\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ;
end
% --------------------------------------------------------------------
% Compile
% --------------------------------------------------------------------
% Intermediate object files
srcs = horzcat(lib_src,mex_src) ;
for i = 1:numel(horzcat(lib_src, mex_src))
[~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ;
objfile = toobj(bld_dir,srcs{i});
if strcmp(ext,'cu')
if strcmp(opts.cudaMethod,'nvcc')
nvcc_compile(opts, srcs{i}, objfile, flags.nvcc) ;
else
mex_compile(opts, srcs{i}, objfile, flags.mexcu) ;
end
else
mex_compile(opts, srcs{i}, objfile, flags.mexcc) ;
end
assert(exist(objfile, 'file') ~= 0, 'Compilation of %s failed.', objfile);
end
% Link into MEX files
for i = 1:numel(mex_src)
objs = toobj(bld_dir, [mex_src(i), lib_src]) ;
mex_link(opts, objs, mex_dir, flags.mexlink) ;
end
% Reset path adding the mex subdirectory just created
vl_setupnn() ;
% --------------------------------------------------------------------
% Utility functions
% --------------------------------------------------------------------
% --------------------------------------------------------------------
function objs = toobj(bld_dir,srcs)
% --------------------------------------------------------------------
str = fullfile('matlab','src') ;
multiple = iscell(srcs) ;
if ~multiple, srcs = {srcs} ; end
objs = cell(1, numel(srcs));
for t = 1:numel(srcs)
i = strfind(srcs{t},str);
objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ;
end
if ~multiple, objs = objs{1} ; end
objs = regexprep(objs,'.cpp$',['.' objext]) ;
objs = regexprep(objs,'.cu$',['.' objext]) ;
objs = regexprep(objs,'.c$',['.' objext]) ;
% --------------------------------------------------------------------
function mex_compile(opts, src, tgt, mex_opts)
% --------------------------------------------------------------------
mopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ;
opts.verbose && fprintf('%s: MEX CC: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function nvcc_compile(opts, src, tgt, nvcc_opts)
% --------------------------------------------------------------------
nvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc');
nvcc_cmd = sprintf('"%s" -c "%s" %s -o "%s"', ...
nvcc_path, src, ...
strjoin(nvcc_opts), tgt);
opts.verbose && fprintf('%s: NVCC CC: %s\n', mfilename, nvcc_cmd) ;
status = system(nvcc_cmd);
if status, error('Command %s failed.', nvcc_cmd); end;
% --------------------------------------------------------------------
function mex_link(opts, objs, mex_dir, mex_flags)
% --------------------------------------------------------------------
mopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ;
opts.verbose && fprintf('%s: MEX LINK: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function ext = objext()
% --------------------------------------------------------------------
% Get the extension for an 'object' file for the current computer
% architecture
switch computer('arch')
case 'win64', ext = 'obj';
case {'maci64', 'glnxa64'}, ext = 'o' ;
otherwise, error('Unsupported architecture %s.', computer) ;
end
% --------------------------------------------------------------------
function conf_file = mex_cuda_config(root)
% --------------------------------------------------------------------
% Get mex CUDA config file
mver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ;
if mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end
arch = computer('arch') ;
switch arch
case {'win64'}
config_dir = fullfile(matlabroot, 'toolbox', ...
'distcomp', 'gpu', 'extern', ...
'src', 'mex', arch) ;
case {'maci64', 'glnxa64'}
config_dir = fullfile(root, 'matlab', 'src', 'config') ;
end
conf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]);
fprintf('%s:\tCUDA: MEX config file: ''%s''\n', mfilename, conf_file);
% --------------------------------------------------------------------
function cl_path = check_clpath()
% --------------------------------------------------------------------
% Checks whether the cl.exe is in the path (needed for the nvcc). If
% not, tries to guess the location out of mex configuration.
cc = mex.getCompilerConfigurations('c++');
if isempty(cc)
error(['Mex is not configured.'...
'Run "mex -setup" to configure your compiler. See ',...
'http://www.mathworks.com/support/compilers ', ...
'for supported compilers for your platform.']);
end
cl_path = fullfile(cc.Location, 'VC', 'bin', 'amd64');
[status, ~] = system('cl.exe -help');
if status == 1
warning('CL.EXE not found in PATH. Trying to guess out of mex setup.');
prev_path = getenv('PATH');
setenv('PATH', [prev_path ';' cl_path]);
status = system('cl.exe');
if status == 1
setenv('PATH', prev_path);
error('Unable to find cl.exe');
else
fprintf('Location of cl.exe (%s) successfully added to your PATH.\n', ...
cl_path);
end
end
% -------------------------------------------------------------------------
function paths = which_nvcc()
% -------------------------------------------------------------------------
switch computer('arch')
case 'win64'
[~, paths] = system('where nvcc.exe');
paths = strtrim(paths);
paths = paths(strfind(paths, '.exe'));
case {'maci64', 'glnxa64'}
[~, paths] = system('which nvcc');
paths = strtrim(paths) ;
end
% -------------------------------------------------------------------------
function cuda_root = search_cuda_devkit(opts)
% -------------------------------------------------------------------------
% This function tries to to locate a working copy of the CUDA Devkit.
opts.verbose && fprintf(['%s:\tCUDA: searching for the CUDA Devkit' ...
' (use the option ''CudaRoot'' to override):\n'], mfilename);
% Propose a number of candidate paths for NVCC
paths = {getenv('MW_NVCC_PATH')} ;
paths = [paths, which_nvcc()] ;
for v = {'5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0'}
switch computer('arch')
case 'glnxa64'
paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ;
case 'maci64'
paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ;
case 'win64'
paths{end+1} = sprintf('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v%s\\bin\\nvcc.exe', char(v)) ;
end
end
paths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ;
% Validate each candidate NVCC path
for i=1:numel(paths)
nvcc(i).path = paths{i} ;
[nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(paths{i}) ;
end
if opts.verbose
fprintf('\t| %5s | %5s | %-70s |\n', 'valid', 'ver', 'NVCC path') ;
for i=1:numel(paths)
fprintf('\t| %5d | %5d | %-70s |\n', ...
nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ;
end
end
% Pick an entry
index = find([nvcc.isvalid]) ;
if isempty(index)
error('Could not find a valid NVCC executable\n') ;
end
[~, newest] = max([nvcc(index).version]);
nvcc = nvcc(index(newest)) ;
cuda_root = fileparts(fileparts(nvcc.path)) ;
if opts.verbose
fprintf('%s:\tCUDA: choosing NVCC compiler ''%s'' (version %d)\n', ...
mfilename, nvcc.path, nvcc.version) ;
end
% -------------------------------------------------------------------------
function [valid, cuver] = validate_nvcc(nvccPath)
% -------------------------------------------------------------------------
[status, output] = system(sprintf('"%s" --version', nvccPath)) ;
valid = (status == 0) ;
if ~valid
cuver = 0 ;
return ;
end
match = regexp(output, 'V(\d+\.\d+\.\d+)', 'match') ;
if isempty(match), valid = false ; return ; end
cuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ;
% --------------------------------------------------------------------
function cuver = activate_nvcc(nvccPath)
% --------------------------------------------------------------------
% Validate the NVCC compiler installation
[valid, cuver] = validate_nvcc(nvccPath) ;
if ~valid
error('The NVCC compiler ''%s'' does not appear to be valid.', nvccPath) ;
end
% Make sure that NVCC is visible by MEX by setting the MW_NVCC_PATH
% environment variable to the NVCC compiler path
if ~strcmp(getenv('MW_NVCC_PATH'), nvccPath)
warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', nvccPath) ;
setenv('MW_NVCC_PATH', nvccPath) ;
end
% In some operating systems and MATLAB versions, NVCC must also be
% available in the command line search path. Make sure that this is%
% the case.
[valid_, cuver_] = validate_nvcc('nvcc') ;
if ~valid_ || cuver_ ~= cuver
warning('NVCC not found in the command line path or the one found does not matches ''%s''.', nvccPath);
nvccDir = fileparts(nvccPath) ;
prevPath = getenv('PATH') ;
switch computer
case 'PCWIN64', separator = ';' ;
case {'GLNXA64', 'MACI64'}, separator = ':' ;
end
setenv('PATH', [nvccDir separator prevPath]) ;
[valid_, cuver_] = validate_nvcc('nvcc') ;
if ~valid_ || cuver_ ~= cuver
setenv('PATH', prevPath) ;
error('Unable to set the command line path to point to ''%s'' correctly.', nvccPath) ;
else
fprintf('Location of NVCC (%s) added to your command search PATH.\n', nvccDir) ;
end
end
% -------------------------------------------------------------------------
function str = quote_nvcc(str)
% -------------------------------------------------------------------------
if iscell(str), str = strjoin(str) ; end
str = strrep(strtrim(str), ' ', ',') ;
if ~isempty(str), str = ['-Xcompiler ' str] ; end
% --------------------------------------------------------------------
function cudaArch = get_cuda_arch(opts)
% --------------------------------------------------------------------
opts.verbose && fprintf('%s:\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\n', mfilename);
try
gpu_device = gpuDevice();
arch_code = strrep(gpu_device.ComputeCapability, '.', '');
cudaArch = ...
sprintf('-gencode=arch=compute_%s,code=\\\"sm_%s,compute_%s\\\" ', ...
arch_code, arch_code, arch_code) ;
catch
opts.verbose && fprintf(['%s:\tCUDA: cannot determine the capabilities of the installed GPU; ' ...
'falling back to default\n'], mfilename);
cudaArch = opts.defCudaArch;
end
|
github
|
maxkferg/casting-defect-detection-master
|
getVarReceptiveFields.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/+dagnn/@DagNN/getVarReceptiveFields.m
| 3,633 |
utf_8
|
d0bd8171e7f72fe003abbc2f859b0678
|
function rfs = getVarReceptiveFields(obj, var)
%GETVARRECEPTIVEFIELDS Get the receptive field of a variable
% RFS = GETVARRECEPTIVEFIELDS(OBJ, VAR) gets the receptivie fields RFS of
% all the variables of the DagNN OBJ into variable VAR. VAR is a variable
% name or index.
%
% RFS has one entry for each variable in the DagNN following the same
% format as has DAGNN.GETRECEPTIVEFIELDS(). For example, RFS(i) is the
% receptive field of the i-th variable in the DagNN into variable VAR. If
% the i-th variable is not a descendent of VAR in the DAG, then there is
% no receptive field, indicated by `rfs(i).size == []`. If the receptive
% field cannot be computed (e.g. because it depends on the values of
% variables and not just on the network topology, or if it cannot be
% expressed as a sliding window), then `rfs(i).size = [NaN NaN]`.
% Copyright (C) 2015 Karel Lenc and 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 ~isnumeric(var)
var_n = obj.getVarIndex(var) ;
if isnan(var_n)
error('Variable %s not found.', var);
end
var = var_n;
end
nv = numel(obj.vars) ;
nw = numel(var) ;
rfs = struct('size', cell(nw, nv), 'stride', cell(nw, nv), 'offset', cell(nw,nv)) ;
for w = 1:numel(var)
rfs(w,var(w)).size = [1 1] ;
rfs(w,var(w)).stride = [1 1] ;
rfs(w,var(w)).offset = [1 1] ;
end
for l = obj.executionOrder
% visit all blocks and get their receptive fields
in = obj.layers(l).inputIndexes ;
out = obj.layers(l).outputIndexes ;
blockRfs = obj.layers(l).block.getReceptiveFields() ;
for w = 1:numel(var)
% find the receptive fields in each of the inputs of the block
for i = 1:numel(in)
for j = 1:numel(out)
rf = composeReceptiveFields(rfs(w, in(i)), blockRfs(i,j)) ;
rfs(w, out(j)) = resolveReceptiveFields([rfs(w, out(j)), rf]) ;
end
end
end
end
end
% -------------------------------------------------------------------------
function rf = composeReceptiveFields(rf1, rf2)
% -------------------------------------------------------------------------
if isempty(rf1.size) || isempty(rf2.size)
rf.size = [] ;
rf.stride = [] ;
rf.offset = [] ;
return ;
end
rf.size = rf1.stride .* (rf2.size - 1) + rf1.size ;
rf.stride = rf1.stride .* rf2.stride ;
rf.offset = rf1.stride .* (rf2.offset - 1) + rf1.offset ;
end
% -------------------------------------------------------------------------
function rf = resolveReceptiveFields(rfs)
% -------------------------------------------------------------------------
rf.size = [] ;
rf.stride = [] ;
rf.offset = [] ;
for i = 1:numel(rfs)
if isempty(rfs(i).size), continue ; end
if isnan(rfs(i).size)
rf.size = [NaN NaN] ;
rf.stride = [NaN NaN] ;
rf.offset = [NaN NaN] ;
break ;
end
if isempty(rf.size)
rf = rfs(i) ;
else
if ~isequal(rf.stride,rfs(i).stride)
% incompatible geometry; this cannot be represented by a sliding
% window RF field and may denotes an error in the network structure
rf.size = [NaN NaN] ;
rf.stride = [NaN NaN] ;
rf.offset = [NaN NaN] ;
break;
else
% the two RFs have the same stride, so they can be recombined
% the new RF is just large enough to contain both of them
a = rf.offset - (rf.size-1)/2 ;
b = rf.offset + (rf.size-1)/2 ;
c = rfs(i).offset - (rfs(i).size-1)/2 ;
d = rfs(i).offset + (rfs(i).size-1)/2 ;
e = min(a,c) ;
f = max(b,d) ;
rf.offset = (e+f)/2 ;
rf.size = f-e+1 ;
end
end
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
rebuild.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/+dagnn/@DagNN/rebuild.m
| 3,243 |
utf_8
|
e368536d9e70c805d8424cdd6b593960
|
function rebuild(obj)
%REBUILD Rebuild the internal data structures of a DagNN object
% REBUILD(obj) rebuilds the internal data structures
% of the DagNN obj. It is an helper function used internally
% to update the network when layers are added or removed.
varFanIn = zeros(1, numel(obj.vars)) ;
varFanOut = zeros(1, numel(obj.vars)) ;
parFanOut = zeros(1, numel(obj.params)) ;
for l = 1:numel(obj.layers)
ii = obj.getVarIndex(obj.layers(l).inputs) ;
oi = obj.getVarIndex(obj.layers(l).outputs) ;
pi = obj.getParamIndex(obj.layers(l).params) ;
obj.layers(l).inputIndexes = ii ;
obj.layers(l).outputIndexes = oi ;
obj.layers(l).paramIndexes = pi ;
varFanOut(ii) = varFanOut(ii) + 1 ;
varFanIn(oi) = varFanIn(oi) + 1 ;
parFanOut(pi) = parFanOut(pi) + 1 ;
end
[obj.vars.fanin] = tolist(num2cell(varFanIn)) ;
[obj.vars.fanout] = tolist(num2cell(varFanOut)) ;
if ~isempty(parFanOut)
[obj.params.fanout] = tolist(num2cell(parFanOut)) ;
end
% dump unused variables
keep = (varFanIn + varFanOut) > 0 ;
obj.vars = obj.vars(keep) ;
varRemap = cumsum(keep) ;
% dump unused parameters
keep = parFanOut > 0 ;
obj.params = obj.params(keep) ;
parRemap = cumsum(keep) ;
% update the indexes to account for removed layers, variables and parameters
for l = 1:numel(obj.layers)
obj.layers(l).inputIndexes = varRemap(obj.layers(l).inputIndexes) ;
obj.layers(l).outputIndexes = varRemap(obj.layers(l).outputIndexes) ;
obj.layers(l).paramIndexes = parRemap(obj.layers(l).paramIndexes) ;
obj.layers(l).block.layerIndex = l ;
end
% update the variable and parameter names hash maps
obj.varNames = cell2struct(num2cell(1:numel(obj.vars)), {obj.vars.name}, 2) ;
obj.paramNames = cell2struct(num2cell(1:numel(obj.params)), {obj.params.name}, 2) ;
obj.layerNames = cell2struct(num2cell(1:numel(obj.layers)), {obj.layers.name}, 2) ;
% determine the execution order again (and check for consistency)
obj.executionOrder = getOrder(obj) ;
% --------------------------------------------------------------------
function order = getOrder(obj)
% --------------------------------------------------------------------
hops = cell(1, numel(obj.vars)) ;
for l = 1:numel(obj.layers)
for v = obj.layers(l).inputIndexes
hops{v}(end+1) = l ;
end
end
order = zeros(1, numel(obj.layers)) ;
for l = 1:numel(obj.layers)
if order(l) == 0
order = dagSort(obj, hops, order, l) ;
end
end
if any(order == -1)
warning('The network graph contains a cycle') ;
end
[~,order] = sort(order, 'descend') ;
% --------------------------------------------------------------------
function order = dagSort(obj, hops, order, layer)
% --------------------------------------------------------------------
if order(layer) > 0, return ; end
order(layer) = -1 ; % mark as open
n = 0 ;
for o = obj.layers(layer).outputIndexes ;
for child = hops{o}
if order(child) == -1
return ;
end
if order(child) == 0
order = dagSort(obj, hops, order, child) ;
end
n = max(n, order(child)) ;
end
end
order(layer) = n + 1 ;
% --------------------------------------------------------------------
function varargout = tolist(x)
% --------------------------------------------------------------------
[varargout{1:numel(x)}] = x{:} ;
|
github
|
maxkferg/casting-defect-detection-master
|
print.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/+dagnn/@DagNN/print.m
| 15,032 |
utf_8
|
7da4e68e624f559f815ee3076d9dd966
|
function str = print(obj, inputSizes, varargin)
%PRINT Print information about the DagNN object
% PRINT(OBJ) displays a summary of the functions and parameters in the network.
% STR = PRINT(OBJ) returns the summary as a string instead of printing it.
%
% PRINT(OBJ, INPUTSIZES) where INPUTSIZES is a cell array of the type
% {'input1nam', input1size, 'input2name', input2size, ...} prints
% information using the specified size for each of the listed inputs.
%
% PRINT(___, 'OPT', VAL, ...) accepts the following options:
%
% `All`:: false
% Display all the information below.
%
% `Layers`:: '*'
% Specify which layers to print. This can be either a list of
% indexes, a cell array of array names, or the string '*', meaning
% all layers.
%
% `Parameters`:: '*'
% Specify which parameters to print, similar to the option above.
%
% `Variables`:: []
% Specify which variables to print, similar to the option above.
%
% `Dependencies`:: false
% Whether to display the dependency (geometric transformation)
% of each variables from each input.
%
% `Format`:: 'ascii'
% Choose between `ascii`, `latex`, `csv`, 'digraph', and `dot`.
% The first three format print tables; `digraph` uses the plot function
% for a `digraph` (supported in MATLAB>=R2015b) and the last one
% prints a graph in `dot` format. In case of zero outputs, it
% attmepts to compile and visualise the dot graph using `dot` command
% and `start` (Windows), `display` (Linux) or `open` (Mac OSX) on your system.
% In the latter case, all variables and layers are included in the
% graph, regardless of the other parameters.
%
% `FigurePath`:: 'tempname.pdf'
% Sets the path where any generated `dot` figure will be saved. Currently,
% this is useful only in combination with the format `dot`.
% By default, a unique temporary filename is used (`tempname`
% is replaced with a `tempname()` call). The extension specifies the
% output format (passed to dot as a `-Text` parameter).
% If not extension provided, PDF used by default.
% Additionally, stores the .dot file used to generate the figure to
% the same location.
%
% `dotArgs`:: ''
% Additional dot arguments. E.g. '-Gsize="7"' to generate a smaller
% output (for a review of the network structure etc.).
%
% `MaxNumColumns`:: 18
% Maximum number of columns in each table.
%
% See also: DAGNN, DAGNN.GETVARSIZES().
if nargin > 1 && ischar(inputSizes)
% called directly with options, skipping second argument
varargin = {inputSizes, varargin{:}} ;
inputSizes = {} ;
end
opts.all = false ;
opts.format = 'ascii' ;
opts.figurePath = 'tempname.pdf' ;
opts.dotArgs = '';
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.layers = '*' ;
opts.parameters = [] ;
opts.variables = [] ;
if opts.all || nargin > 1
opts.variables = '*' ;
end
if opts.all
opts.parameters = '*' ;
end
opts.memory = true ;
opts.dependencies = opts.all ;
opts.maxNumColumns = 18 ;
opts = vl_argparse(opts, varargin) ;
if nargin == 1, inputSizes = {} ; end
varSizes = obj.getVarSizes(inputSizes) ;
paramSizes = cellfun(@size, {obj.params.value}, 'UniformOutput', false) ;
str = {''} ;
if strcmpi(opts.format, 'dot')
str = printDot(obj, varSizes, paramSizes, opts) ;
if nargout == 0
displayDot(str, opts) ;
end
return ;
end
if strcmpi(opts.format,'digraph')
str = printdigraph(obj, varSizes) ;
return ;
end
if ~isempty(opts.layers)
table = {'func', '-', 'type', 'inputs', 'outputs', 'params', 'pad', 'stride'} ;
for l = select(obj, 'layers', opts.layers)
layer = obj.layers(l) ;
table{l+1,1} = layer.name ;
table{l+1,2} = '-' ;
table{l+1,3} = player(class(layer.block)) ;
table{l+1,4} = strtrim(sprintf('%s ', layer.inputs{:})) ;
table{l+1,5} = strtrim(sprintf('%s ', layer.outputs{:})) ;
table{l+1,6} = strtrim(sprintf('%s ', layer.params{:})) ;
if isprop(layer.block, 'pad')
table{l+1,7} = pdims(layer.block.pad) ;
else
table{l+1,7} = 'n/a' ;
end
if isprop(layer.block, 'stride')
table{l+1,8} = pdims(layer.block.stride) ;
else
table{l+1,8} = 'n/a' ;
end
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if ~isempty(opts.parameters)
table = {'param', '-', 'dims', 'mem', 'fanout'} ;
for v = select(obj, 'params', opts.parameters)
table{v+1,1} = obj.params(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(paramSizes{v}) ;
table{v+1,4} = pmem(prod(paramSizes{v}) * 4) ;
table{v+1,5} = sprintf('%d',obj.params(v).fanout) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if ~isempty(opts.variables)
table = {'var', '-', 'dims', 'mem', 'fanin', 'fanout'} ;
for v = select(obj, 'vars', opts.variables)
table{v+1,1} = obj.vars(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(varSizes{v}) ;
table{v+1,4} = pmem(prod(varSizes{v}) * 4) ;
table{v+1,5} = sprintf('%d',obj.vars(v).fanin) ;
table{v+1,6} = sprintf('%d',obj.vars(v).fanout) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if opts.memory
paramMem = sum(cellfun(@getMem, paramSizes)) ;
varMem = sum(cellfun(@getMem, varSizes)) ;
table = {'params', 'vars', 'total'} ;
table{2,1} = pmem(paramMem) ;
table{2,2} = pmem(varMem) ;
table{2,3} = pmem(paramMem + varMem) ;
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if opts.dependencies
% print variable to input dependencies
inputs = obj.getInputs() ;
rfs = obj.getVarReceptiveFields(inputs) ;
for i = 1:size(rfs,1)
table = {sprintf('rf in ''%s''', inputs{i}), '-', 'size', 'stride', 'offset'} ;
for v = 1:size(rfs,2)
table{v+1,1} = obj.vars(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(rfs(i,v).size) ;
table{v+1,4} = pdims(rfs(i,v).stride) ;
table{v+1,5} = pdims(rfs(i,v).offset) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
end
% finish
str = horzcat(str{:}) ;
if nargout == 0,
fprintf('%s',str) ;
clear str ;
end
end
% -------------------------------------------------------------------------
function str = printtable(opts, table)
% -------------------------------------------------------------------------
str = {''} ;
for i=2:opts.maxNumColumns:size(table,2)
sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;
str{end+1} = printtablechunk(opts, table(:, [1 sel])) ;
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
end
% -------------------------------------------------------------------------
function str = printtablechunk(opts, table)
% -------------------------------------------------------------------------
str = {''} ;
switch opts.format
case 'ascii'
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
for i=1:size(table,1)
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds|', sizes(j)) ;
if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end
str{end+1} = sprintf(fmt, s) ;
end
str{end+1} = sprintf('\n') ;
end
case 'latex'
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds', sizes(j)) ;
str{end+1} = sprintf(fmt, latexesc(s)) ;
if j<size(table,2), str{end+1} = sprintf('&') ; end
end
str{end+1} = sprintf('\\\\\n') ;
end
str{end+1}= sprintf('\\end{tabular}\n') ;
case 'csv'
sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds,', sizes(j)) ;
str{end+1} = sprintf(fmt, ['"' s '"']) ;
end
str{end+1} = sprintf('\n') ;
end
otherwise
error('Uknown format %s', opts.format) ;
end
str = horzcat(str{:}) ;
end
% -------------------------------------------------------------------------
function s = latexesc(s)
% -------------------------------------------------------------------------
s = strrep(s,'\','\\') ;
s = strrep(s,'_','\char`_') ;
end
% -------------------------------------------------------------------------
function s = pmem(x)
% -------------------------------------------------------------------------
if isnan(x), s = 'NaN' ;
elseif x < 1024^1, s = sprintf('%.0fB', x) ;
elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;
elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;
else s = sprintf('%.0fGB', x / 1024^3) ;
end
end
% -------------------------------------------------------------------------
function s = pdims(x)
% -------------------------------------------------------------------------
if all(isnan(x))
s = 'n/a' ;
return ;
end
if all(x==x(1))
s = sprintf('%.4g', x(1)) ;
else
s = sprintf('%.4gx', x(:)) ;
s(end) = [] ;
end
end
% -------------------------------------------------------------------------
function x = player(x)
% -------------------------------------------------------------------------
if numel(x) < 7, return ; end
if x(1:6) == 'dagnn.', x = x(7:end) ; end
end
% -------------------------------------------------------------------------
function m = getMem(sz)
% -------------------------------------------------------------------------
m = prod(sz) * 4 ;
if isnan(m), m = 0 ; end
end
% -------------------------------------------------------------------------
function sel = select(obj, type, pattern)
% -------------------------------------------------------------------------
if isnumeric(pattern)
sel = pattern ;
else
if isstr(pattern)
if strcmp(pattern, '*')
sel = 1:numel(obj.(type)) ;
return ;
else
pattern = {pattern} ;
end
end
sel = find(cellfun(@(x) any(strcmp(x, pattern)), {obj.(type).name})) ;
end
end
% -------------------------------------------------------------------------
function h = printdigraph(net, varSizes)
% -------------------------------------------------------------------------
if exist('digraph') ~= 2
error('MATLAB graph support not present.');
end
s = []; t = []; w = [];
varsNames = {net.vars.name};
layerNames = {net.layers.name};
numVars = numel(varsNames);
spatSize = cellfun(@(vs) vs(1), varSizes);
spatSize(isnan(spatSize)) = 1;
varChannels = cellfun(@(vs) vs(3), varSizes);
varChannels(isnan(varChannels)) = 0;
for li = 1:numel(layerNames)
l = net.layers(li); lidx = numVars + li;
s = [s l.inputIndexes];
t = [t lidx*ones(1, numel(l.inputIndexes))];
w = [w spatSize(l.inputIndexes)];
s = [s lidx*ones(1, numel(l.outputIndexes))];
t = [t l.outputIndexes];
w = [w spatSize(l.outputIndexes)];
end
nodeNames = [varsNames, layerNames];
g = digraph(s, t, w);
lw = 5*g.Edges.Weight/max([g.Edges.Weight; 5]);
h = plot(g, 'NodeLabel', nodeNames, 'LineWidth', lw);
highlight(h, numVars+1:numVars+numel(layerNames), 'MarkerSize', 8, 'Marker', 's');
highlight(h, 1:numVars, 'MarkerSize', 5, 'Marker', 's');
cmap = copper;
varNvalRel = varChannels./max(varChannels);
for vi = 1:numel(varChannels)
highlight(h, vi, 'NodeColor', cmap(max(round(varNvalRel(vi)*64), 1),:));
end
axis off;
layout(h, 'force');
end
% -------------------------------------------------------------------------
function str = printDot(net, varSizes, paramSizes, otps)
% -------------------------------------------------------------------------
str = {} ;
str{end+1} = sprintf('digraph DagNN {\n\tfontsize=12\n') ;
font_style = 'fontsize=12 fontname="helvetica"';
for v = 1:numel(net.vars)
label=sprintf('{{%s} | {%s | %s }}', net.vars(v).name, pdims(varSizes{v}), pmem(4*prod(varSizes{v}))) ;
str{end+1} = sprintf('\tvar_%s [label="%s" shape=record style="solid,rounded,filled" color=cornsilk4 fillcolor=beige %s ]\n', ...
net.vars(v).name, label, font_style) ;
end
for p = 1:numel(net.params)
label=sprintf('{{%s} | {%s | %s }}', net.params(p).name, pdims(paramSizes{p}), pmem(4*prod(paramSizes{p}))) ;
str{end+1} = sprintf('\tpar_%s [label="%s" shape=record style="solid,rounded,filled" color=lightsteelblue4 fillcolor=lightsteelblue %s ]\n', ...
net.params(p).name, label, font_style) ;
end
for l = 1:numel(net.layers)
label = sprintf('{ %s | %s }', net.layers(l).name, class(net.layers(l).block)) ;
str{end+1} = sprintf('\t%s [label="%s" shape=record style="bold,filled" color="tomato4" fillcolor="tomato" %s ]\n', ...
net.layers(l).name, label, font_style) ;
for i = 1:numel(net.layers(l).inputs)
str{end+1} = sprintf('\tvar_%s->%s [weight=10]\n', ...
net.layers(l).inputs{i}, ...
net.layers(l).name) ;
end
for o = 1:numel(net.layers(l).outputs)
str{end+1} = sprintf('\t%s->var_%s [weight=10]\n', ...
net.layers(l).name, ...
net.layers(l).outputs{o}) ;
end
for p = 1:numel(net.layers(l).params)
str{end+1} = sprintf('\tpar_%s->%s [weight=1]\n', ...
net.layers(l).params{p}, ...
net.layers(l).name) ;
end
end
str{end+1} = sprintf('}\n') ;
str = cat(2,str{:}) ;
end
% -------------------------------------------------------------------------
function displayDot(str, opts)
% -------------------------------------------------------------------------
%mwdot = fullfile(matlabroot, 'bin', computer('arch'), 'mwdot') ;
dotPaths = {'/opt/local/bin/dot', 'dot'} ;
if ismember(computer, {'PCWIN64', 'PCWIN'})
winPath = 'c:\Program Files (x86)';
dpath = dir(fullfile(winPath, 'Graphviz*'));
if ~isempty(dpath)
dotPaths = [{fullfile(winPath, dpath.name, 'bin', 'dot.exe')}, dotPaths];
end
end
dotExe = '' ;
for i = 1:numel(dotPaths)
[~,~,ext] = fileparts(dotPaths{i});
if exist(dotPaths{i},'file') && ~strcmp(ext, '.m')
dotExe = dotPaths{i} ;
break;
end
end
if isempty(dotExe)
warning('Could not genereate a figure because the `dot` utility could not be found.') ;
return ;
end
[path, figName, ext] = fileparts(opts.figurePath) ;
if isempty(ext), ext = '.pdf' ; end
if strcmp(figName, 'tempname')
figName = tempname();
end
in = fullfile(path, [ figName, '.dot' ]) ;
out = fullfile(path, [ figName, ext ]) ;
f = fopen(in, 'w') ; fwrite(f, str) ; fclose(f) ;
cmd = sprintf('"%s" -T%s %s -o "%s" "%s"', dotExe, ext(2:end), ...
opts.dotArgs, out, in) ;
[status, result] = system(cmd) ;
if status ~= 0
error('Unable to run %s\n%s', cmd, result) ;
end
if ~isempty(strtrim(result))
fprintf('Dot output:\n%s\n', result) ;
end
%f = fopen(out,'r') ; file=fread(f, 'char=>char')' ; fclose(f) ;
switch computer
case {'PCWIN64', 'PCWIN'}
system(sprintf('start "" "%s"', out)) ;
case 'MACI64'
system(sprintf('open "%s"', out)) ;
case 'GLNXA64'
system(sprintf('display "%s"', out)) ;
otherwise
fprintf('The figure saved at "%s"\n', out) ;
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
fromSimpleNN.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/+dagnn/@DagNN/fromSimpleNN.m
| 7,258 |
utf_8
|
83f914aec610125592263d74249f54a7
|
function obj = fromSimpleNN(net, varargin)
% FROMSIMPLENN Initialize a DagNN object from a SimpleNN network
% FROMSIMPLENN(NET) initializes the DagNN object from the
% specified CNN using the SimpleNN format.
%
% SimpleNN objects are linear chains of computational layers. These
% layers exchange information through variables and parameters that
% are not explicitly named. Hence, FROMSIMPLENN() uses a number of
% rules to assign such names automatically:
%
% * From the input to the output of the CNN, variables are called
% `x0` (input of the first layer), `x1`, `x2`, .... In this
% manner `xi` is the output of the i-th layer.
%
% * Any loss layer requires two inputs, the second being a label.
% These are called `label` (for the first such layers), and then
% `label2`, `label3`,... for any other similar layer.
%
% Additionally, given the option `CanonicalNames` the function can
% change the names of some variables to make them more convenient to
% use. With this option turned on:
%
% * The network input is called `input` instead of `x0`.
%
% * The output of each SoftMax layer is called `prob` (or `prob2`,
% ...).
%
% * The output of each Loss layer is called `objective` (or `
% objective2`, ...).
%
% * The input of each SoftMax or Loss layer of type *softmax log
% loss* is called `prediction` (or `prediction2`, ...). If a Loss
% layer immediately follows a SoftMax layer, then the rule above
% takes precendence and the input name is not changed.
%
% FROMSIMPLENN(___, 'OPT', VAL, ...) accepts the following options:
%
% `CanonicalNames`:: false
% If `true` use the rules above to assign more meaningful
% names to some of the variables.
% Copyright (C) 2015 Karel Lenc and 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).
opts.canonicalNames = false ;
opts = vl_argparse(opts, varargin) ;
import dagnn.*
obj = DagNN() ;
net = vl_simplenn_move(net, 'cpu') ;
net = vl_simplenn_tidy(net) ;
% copy meta-information as is
obj.meta = net.meta ;
for l = 1:numel(net.layers)
inputs = {sprintf('x%d',l-1)} ;
outputs = {sprintf('x%d',l)} ;
params = struct(...
'name', {}, ...
'value', {}, ...
'learningRate', [], ...
'weightDecay', []) ;
if isfield(net.layers{l}, 'name')
name = net.layers{l}.name ;
else
name = sprintf('layer%d',l) ;
end
switch net.layers{l}.type
case {'conv', 'convt'}
sz = size(net.layers{l}.weights{1}) ;
hasBias = ~isempty(net.layers{l}.weights{2}) ;
params(1).name = sprintf('%sf',name) ;
params(1).value = net.layers{l}.weights{1} ;
if hasBias
params(2).name = sprintf('%sb',name) ;
params(2).value = net.layers{l}.weights{2} ;
end
if isfield(net.layers{l},'learningRate')
params(1).learningRate = net.layers{l}.learningRate(1) ;
if hasBias
params(2).learningRate = net.layers{l}.learningRate(2) ;
end
end
if isfield(net.layers{l},'weightDecay')
params(1).weightDecay = net.layers{l}.weightDecay(1) ;
if hasBias
params(2).weightDecay = net.layers{l}.weightDecay(2) ;
end
end
switch net.layers{l}.type
case 'conv'
block = Conv() ;
block.size = sz ;
block.pad = net.layers{l}.pad ;
block.stride = net.layers{l}.stride ;
block.dilate = net.layers{l}.dilate ;
case 'convt'
block = ConvTranspose() ;
block.size = sz ;
block.upsample = net.layers{l}.upsample ;
block.crop = net.layers{l}.crop ;
block.numGroups = net.layers{l}.numGroups ;
end
block.hasBias = hasBias ;
block.opts = net.layers{l}.opts ;
case 'pool'
block = Pooling() ;
block.method = net.layers{l}.method ;
block.poolSize = net.layers{l}.pool ;
block.pad = net.layers{l}.pad ;
block.stride = net.layers{l}.stride ;
block.opts = net.layers{l}.opts ;
case {'normalize', 'lrn'}
block = LRN() ;
block.param = net.layers{l}.param ;
case {'dropout'}
block = DropOut() ;
block.rate = net.layers{l}.rate ;
case {'relu'}
block = ReLU() ;
block.leak = net.layers{l}.leak ;
case {'sigmoid'}
block = Sigmoid() ;
case {'softmax'}
block = SoftMax() ;
case {'softmaxloss'}
block = Loss('loss', 'softmaxlog') ;
% The loss has two inputs
inputs{2} = getNewVarName(obj, 'label') ;
case {'bnorm'}
block = BatchNorm() ;
params(1).name = sprintf('%sm',name) ;
params(1).value = net.layers{l}.weights{1} ;
params(2).name = sprintf('%sb',name) ;
params(2).value = net.layers{l}.weights{2} ;
params(3).name = sprintf('%sx',name) ;
params(3).value = net.layers{l}.weights{3} ;
if isfield(net.layers{l},'learningRate')
params(1).learningRate = net.layers{l}.learningRate(1) ;
params(2).learningRate = net.layers{l}.learningRate(2) ;
params(3).learningRate = net.layers{l}.learningRate(3) ;
end
if isfield(net.layers{l},'weightDecay')
params(1).weightDecay = net.layers{l}.weightDecay(1) ;
params(2).weightDecay = net.layers{l}.weightDecay(2) ;
params(3).weightDecay = 0 ;
end
otherwise
error([net.layers{l}.type ' is unsupported']) ;
end
obj.addLayer(...
name, ...
block, ...
inputs, ...
outputs, ...
{params.name}) ;
for p = 1:numel(params)
pindex = obj.getParamIndex(params(p).name) ;
if ~isempty(params(p).value)
obj.params(pindex).value = params(p).value ;
end
if ~isempty(params(p).learningRate)
obj.params(pindex).learningRate = params(p).learningRate ;
end
if ~isempty(params(p).weightDecay)
obj.params(pindex).weightDecay = params(p).weightDecay ;
end
end
end
% --------------------------------------------------------------------
% Rename variables to canonical names
% --------------------------------------------------------------------
if opts.canonicalNames
for l = 1:numel(obj.layers)
if l == 1
obj.renameVar(obj.layers(l).inputs{1}, 'input') ;
end
if isa(obj.layers(l).block, 'dagnn.SoftMax')
obj.renameVar(obj.layers(l).outputs{1}, getNewVarName(obj, 'prob')) ;
obj.renameVar(obj.layers(l).inputs{1}, getNewVarName(obj, 'prediction')) ;
end
if isa(obj.layers(l).block, 'dagnn.Loss')
obj.renameVar(obj.layers(l).outputs{1}, 'objective') ;
if isempty(regexp(obj.layers(l).inputs{1}, '^prob.*'))
obj.renameVar(obj.layers(l).inputs{1}, ...
getNewVarName(obj, 'prediction')) ;
end
end
end
end
if isfield(obj.meta, 'inputs')
obj.meta.inputs(1).name = obj.layers(1).inputs{1} ;
end
% --------------------------------------------------------------------
function name = getNewVarName(obj, prefix)
% --------------------------------------------------------------------
t = 0 ;
name = prefix ;
while any(strcmp(name, {obj.vars.name}))
t = t + 1 ;
name = sprintf('%s%d', prefix, t) ;
end
|
github
|
maxkferg/casting-defect-detection-master
|
vl_simplenn_display.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/simplenn/vl_simplenn_display.m
| 12,455 |
utf_8
|
65bb29cd7c27b68c75fdd27acbd63e2b
|
function [info, str] = vl_simplenn_display(net, varargin)
%VL_SIMPLENN_DISPLAY Display the structure of a SimpleNN network.
% VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.
%
% INFO = VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO
% with several statistics for each layer of the network NET.
%
% [INFO, STR] = VL_SIMPLENN_DISPLAY(...) returns also a string STR
% with the text that would otherwise be printed.
%
% The function accepts the following options:
%
% `inputSize`:: auto
% Specifies the size of the input tensor X that will be passed to
% the network as input. This information is used in order to
% estiamte the memory required to process the network. When this
% option is not used, VL_SIMPLENN_DISPLAY() tires to use values
% in the NET structure to guess the input size:
% NET.META.INPUTSIZE and NET.META.NORMALIZATION.IMAGESIZE
% (assuming a batch size of one image, unless otherwise specified
% by the `batchSize` option).
%
% `batchSize`:: []
% Specifies the number of data points in a batch in estimating
% the memory consumption, overriding the last dimension of
% `inputSize`.
%
% `maxNumColumns`:: 18
% Maximum number of columns in a table. Wider tables are broken
% into multiple smaller ones.
%
% `format`:: `'ascii'`
% One of `'ascii'`, `'latex'`, or `'csv'`.
%
% See also: VL_SIMPLENN().
% Copyright (C) 2014-15 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).
opts.inputSize = [] ;
opts.batchSize = [] ;
opts.maxNumColumns = 18 ;
opts.format = 'ascii' ;
opts = vl_argparse(opts, varargin) ;
% determine input size, using first the option, then net.meta.inputSize,
% and eventually net.meta.normalization.imageSize, if any
if isempty(opts.inputSize)
tmp = [] ;
opts.inputSize = [NaN;NaN;NaN;1] ;
if isfield(net, 'meta')
if isfield(net.meta, 'inputSize')
tmp = net.meta.inputSize(:) ;
elseif isfield(net.meta, 'normalization') && ...
isfield(net.meta.normalization, 'imageSize')
tmp = net.meta.normalization.imageSize ;
end
opts.inputSize(1:numel(tmp)) = tmp(:) ;
end
end
if ~isempty(opts.batchSize)
opts.inputSize(4) = opts.batchSize ;
end
fields={'layer', 'type', 'name', '-', ...
'support', 'filtd', 'filtdil', 'nfilt', 'stride', 'pad', '-', ...
'rfsize', 'rfoffset', 'rfstride', '-', ...
'dsize', 'ddepth', 'dnum', '-', ...
'xmem', 'wmem'};
% get the support, stride, and padding of the operators
for l = 1:numel(net.layers)
ly = net.layers{l} ;
switch ly.type
case 'conv'
ks = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ;
ks = (ks - 1) .* ly.dilate + 1 ;
info.support(1:2,l) = ks ;
case 'pool'
info.support(1:2,l) = ly.pool(:) ;
otherwise
info.support(1:2,l) = [1;1] ;
end
if isfield(ly, 'stride')
info.stride(1:2,l) = ly.stride(:) ;
else
info.stride(1:2,l) = 1 ;
end
if isfield(ly, 'pad')
info.pad(1:4,l) = ly.pad(:) ;
else
info.pad(1:4,l) = 0 ;
end
% operator applied to the input image
info.receptiveFieldSize(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
(info.support(1:2,1:l)-1),2) ;
info.receptiveFieldOffset(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ;
info.receptiveFieldStride = cumprod(info.stride,2) ;
end
% get the dimensions of the data
info.dataSize(1:4,1) = opts.inputSize(:) ;
for l = 1:numel(net.layers)
ly = net.layers{l} ;
if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize')
sz = ly.getForwardSize(ly, info.dataSize(:,l)) ;
info.dataSize(:,l+1) = sz(:) ;
continue ;
end
info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ...
sum(info.pad(1:2,l)) - ...
info.support(1,l)) / info.stride(1,l)) + 1 ;
info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ...
sum(info.pad(3:4,l)) - ...
info.support(2,l)) / info.stride(2,l)) + 1 ;
info.dataSize(3, l+1) = info.dataSize(3,l) ;
info.dataSize(4, l+1) = info.dataSize(4,l) ;
switch ly.type
case 'conv'
if isfield(ly, 'weights')
f = ly.weights{1} ;
else
f = ly.filters ;
end
if size(f, 3) ~= 0
info.dataSize(3, l+1) = size(f,4) ;
end
case {'loss', 'softmaxloss'}
info.dataSize(3:4, l+1) = 1 ;
case 'custom'
info.dataSize(3,l+1) = NaN ;
end
end
if nargout == 1, return ; end
% print table
table = {} ;
wmem = 0 ;
xmem = 0 ;
for wi=1:numel(fields)
w = fields{wi} ;
switch w
case 'type', s = 'type' ;
case 'stride', s = 'stride' ;
case 'rfsize', s = 'rf size' ;
case 'rfstride', s = 'rf stride' ;
case 'rfoffset', s = 'rf offset' ;
case 'dsize', s = 'data size' ;
case 'ddepth', s = 'data depth' ;
case 'dnum', s = 'data num' ;
case 'nfilt', s = 'num filts' ;
case 'filtd', s = 'filt dim' ;
case 'filtdil', s = 'filt dilat' ;
case 'wmem', s = 'param mem' ;
case 'xmem', s = 'data mem' ;
otherwise, s = char(w) ;
end
table{wi,1} = s ;
% do input pseudo-layer
for l=0:numel(net.layers)
switch char(w)
case '-', s='-' ;
case 'layer', s=sprintf('%d', l) ;
case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ;
case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ;
case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ;
case 'xmem'
a = prod(info.dataSize(:,l+1)) * 4 ;
s = pmem(a) ;
xmem = xmem + a ;
otherwise
if l == 0
if strcmp(char(w),'type'), s = 'input';
else s = 'n/a' ; end
else
ly=net.layers{l} ;
switch char(w)
case 'name'
if isfield(ly, 'name')
s=ly.name ;
else
s='' ;
end
case 'type'
switch ly.type
case 'normalize', s='norm';
case 'pool'
if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end
case 'softmax', s='softmx' ;
case 'softmaxloss', s='softmxl' ;
otherwise s=ly.type ;
end
case 'nfilt'
switch ly.type
case 'conv'
if isfield(ly, 'weights'), a = size(ly.weights{1},4) ;
else, a = size(ly.filters,4) ; end
s=sprintf('%d',a) ;
otherwise
s='n/a' ;
end
case 'filtd'
switch ly.type
case 'conv'
s=sprintf('%d',size(ly.weights{1},3)) ;
otherwise
s='n/a' ;
end
case 'filtdil'
switch ly.type
case 'conv'
s=sprintf('%d',ly.dilate) ;
otherwise
s='n/a' ;
end
case 'support'
s = pdims(info.support(:,l)) ;
case 'stride'
s = pdims(info.stride(:,l)) ;
case 'pad'
s = pdims(info.pad(:,l)) ;
case 'rfsize'
s = pdims(info.receptiveFieldSize(:,l)) ;
case 'rfoffset'
s = pdims(info.receptiveFieldOffset(:,l)) ;
case 'rfstride'
s = pdims(info.receptiveFieldStride(:,l)) ;
case 'wmem'
a = 0 ;
if isfield(ly, 'weights') ;
for j=1:numel(ly.weights)
a = a + numel(ly.weights{j}) * 4 ;
end
end
% Legacy code to be removed
if isfield(ly, 'filters') ;
a = a + numel(ly.filters) * 4 ;
end
if isfield(ly, 'biases') ;
a = a + numel(ly.biases) * 4 ;
end
s = pmem(a) ;
wmem = wmem + a ;
end
end
end
table{wi,l+2} = s ;
end
end
str = {} ;
for i=2:opts.maxNumColumns:size(table,2)
sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;
str{end+1} = ptable(opts, table(:,[1 sel])) ;
end
table = {...
'parameter memory', sprintf('%s (%.2g parameters)', pmem(wmem), wmem/4);
'data memory', sprintf('%s (for batch size %d)', pmem(xmem), info.dataSize(4,1))} ;
str{end+1} = ptable(opts, table) ;
str = horzcat(str{:}) ;
if nargout == 0
fprintf('%s', str) ;
clear info str ;
end
% -------------------------------------------------------------------------
function str = ptable(opts, table)
% -------------------------------------------------------------------------
switch opts.format
case 'ascii', str = pascii(table) ;
case 'latex', str = platex(table) ;
case 'csv', str = pcsv(table) ;
end
str = horzcat(str,sprintf('\n')) ;
% -------------------------------------------------------------------------
function s = pmem(x)
% -------------------------------------------------------------------------
if isnan(x), s = 'NaN' ;
elseif x < 1024^1, s = sprintf('%.0fB', x) ;
elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;
elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;
else s = sprintf('%.0fGB', x / 1024^3) ;
end
% -------------------------------------------------------------------------
function s = pdims(x)
% -------------------------------------------------------------------------
if all(x==x(1))
s = sprintf('%.4g', x(1)) ;
else
s = sprintf('%.4gx', x(:)) ;
s(end) = [] ;
end
% -------------------------------------------------------------------------
function str = pascii(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
for i=1:size(table,1)
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds|', sizes(j)) ;
if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end
str{end+1} = sprintf(fmt, s) ;
end
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function str = pcsv(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), continue ; end
for j=1:size(table,2)
s = table{i,j} ;
str{end+1} = sprintf('%s,', ['"' s '"']) ;
end
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function str = platex(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds', sizes(j)) ;
str{end+1} = sprintf(fmt, latexesc(s)) ;
if j<size(table,2), str{end+1} = sprintf('&') ; end
end
str{end+1} = sprintf('\\\\\n') ;
end
str{end+1} = sprintf('\\end{tabular}\n') ;
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function s = latexesc(s)
% -------------------------------------------------------------------------
s = strrep(s,'\','\\') ;
s = strrep(s,'_','\char`_') ;
% -------------------------------------------------------------------------
function [cpuMem,gpuMem] = xmem(s, cpuMem, gpuMem)
% -------------------------------------------------------------------------
if nargin <= 1
cpuMem = 0 ;
gpuMem = 0 ;
end
if isstruct(s)
for f=fieldnames(s)'
f = char(f) ;
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s(i).(f), cpuMem, gpuMem) ;
end
end
elseif iscell(s)
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s{i}, cpuMem, gpuMem) ;
end
elseif isnumeric(s)
if isa(s, 'single')
mult = 4 ;
else
mult = 8 ;
end
if isa(s,'gpuArray')
gpuMem = gpuMem + mult * numel(s) ;
else
cpuMem = cpuMem + mult * numel(s) ;
end
end
|
github
|
maxkferg/casting-defect-detection-master
|
vl_test_economic_relu.m
|
.m
|
casting-defect-detection-master/sliding_window/wacv/matconvnet/matlab/xtest/vl_test_economic_relu.m
| 790 |
utf_8
|
35a3dbe98b9a2f080ee5f911630ab6f3
|
% VL_TEST_ECONOMIC_RELU
function vl_test_economic_relu()
x = randn(11,12,8,'single');
w = randn(5,6,8,9,'single');
b = randn(1,9,'single') ;
net.layers{1} = struct('type', 'conv', ...
'filters', w, ...
'biases', b, ...
'stride', 1, ...
'pad', 0);
net.layers{2} = struct('type', 'relu') ;
res = vl_simplenn(net, x) ;
dzdy = randn(size(res(end).x), 'like', res(end).x) ;
clear res ;
res_ = vl_simplenn(net, x, dzdy) ;
res__ = vl_simplenn(net, x, dzdy, [], 'conserveMemory', true) ;
a=whos('res_') ;
b=whos('res__') ;
assert(a.bytes > b.bytes) ;
vl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ;
vl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ;
vl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;
|
github
|
sg-s/puppeteer-master
|
resetSliderBounds.m
|
.m
|
puppeteer-master/@puppeteer/resetSliderBounds.m
| 1,039 |
utf_8
|
82baa1ea06599b50bf5afcd9a8054c78
|
function resetSliderBounds(self,src,event)
if any(self.handles.lbcontrol == src)
% some lower bound being changed
this_param = find(self.handles.lbcontrol == src);
new_bound = event.Value;
if self.handles.sliders(this_param).Value < new_bound
self.handles.sliders(this_param).Value = new_bound;
end
self.handles.sliders(this_param).Limits(1) = new_bound;
elseif any(self.handles.ubcontrol == src)
% some upper bound being changed
this_param = find(self.handles.ubcontrol == src);
new_bound = event.Value;
if self.handles.sliders(this_param).Value > new_bound
self.handles.sliders(this_param).Value = new_bound;
end
self.handles.sliders(this_param).Limits(2) = new_bound;
end
self.handles.sliders(this_param).MinorTicks = linspace(self.handles.lbcontrol(this_param).Value,self.handles.ubcontrol(this_param).Value,21);
self.handles.sliders(this_param).MajorTicks = linspace(self.handles.lbcontrol(this_param).Value,self.handles.ubcontrol(this_param).Value,5);
|
github
|
sg-s/puppeteer-master
|
reset.m
|
.m
|
puppeteer-master/@puppeteer/reset.m
| 1,261 |
utf_8
|
bff70e269444a80480f55ab563c75b2f
|
% callback for the reset button
function reset(self,~,~)
% first copy the original values from the cache to the Pstrings array
for i = 1:length(self.Pstrings)
self.Pstrings(i).Value = self.original_values(i).Value;
end
% now update all the sliders
for i = 1:length(self.handles.sliders)
if self.Pstrings(i).ToggleSwitch
self.handles.sliders(i).Value = self.Pstrings(i).Value;
continue
end
Value = self.Pstrings(i).Value;
if Value > self.handles.sliders(i).Limits(2)
event = struct('Value',Value);
self.handles.ubcontrol(i).Value = Value;
self.resetSliderBounds(self.handles.ubcontrol(i),event);
end
if Value < self.handles.sliders(i).Limits(1)
event = struct('Value',Value);
self.handles.lbcontrol(i).Value = Value;
self.resetSliderBounds(self.handles.lbcontrol(i),event);
end
self.handles.sliders(i).Value = Value;
% update the corresponding control label
this_string = self.handles.controllabel(i).Text;
this_string = this_string(1:strfind(this_string,'='));
this_string = [this_string strlib.oval(Value)];
self.handles.controllabel(i).Text = this_string;
end
if ~isempty(self.valueChangingFcn)
self.valueChangingFcn(self.Pstrings)
elseif ~isempty(self.valueChangedFcn)
self.valueChangedFcn(self.Pstrings)
end
|
github
|
sg-s/puppeteer-master
|
makeUI.m
|
.m
|
puppeteer-master/@puppeteer/makeUI.m
| 4,237 |
utf_8
|
7eccae14684f6674f4bc04a3b561f747
|
function handles = makeUI(self)
warning('off','MATLAB:hg:uicontrol:MinMustBeLessThanMax')
% need to compute the maximum # of controls in each group
group_names = categories([self.Pstrings.Group]);
n_controls = zeros(length(group_names),1);
for i = 1:length(group_names)
this = [self.Pstrings.Group] == group_names{i};
n_controls(i) = sum(this);
end
n_controls = max(n_controls);
% make sure it doesn't spawn off screen
screen_size = get(0,'ScreenSize');
height = min([round(screen_size(4)*.75) self.slider_spacing*(n_controls+1)]);
height = round(height/self.slider_spacing)*self.slider_spacing;
n_rows = height/self.slider_spacing;
screen_size = screen_size(3:4);
x = screen_size(1)/3;
y = screen_size(2) - height - 100;
fig = uifigure('position',[x y 400 height],'Name','puppeteer','Scrollable','on');
fig.MenuBar = 'none';
fig.NumberTitle = 'off';
fig.IntegerHandle = 'off';
fig.CloseRequestFcn = @self.quitManipulateCallback;
fig.Resize = 'off';
fig.Color = 'w';
self.handles.fig = fig;
self.handles.tabgroup = uitabgroup(self.handles.fig);
self.handles.tabgroup.Position = [1 50 400 height-50];
% make a tab for each group
for j = 1:length(group_names)
self.handles.tabs(j) = uitab(self.handles.tabgroup,'Title',group_names{j});
self.handles.tabs(j).Scrollable = 'on';
% figure out the controls in this group
this = [self.Pstrings.Group] == group_names{j};
pstrings = self.Pstrings(this);
ypos = height - sum(this)*self.slider_spacing;
ypos = self.slider_spacing;
for i = 1:length(pstrings)
pidx = find(strcmp(pstrings(i).Name,{self.Pstrings.Name}));
if pstrings(i).ToggleSwitch
sliders(pidx) = uiswitch(self.handles.tabs(j),'ValueChangedFcn',@self.valueChangingCallback,'Items',{pstrings(i).ToggleLeft, pstrings(i).ToggleRight});
sliders(pidx).Position(2) = ypos;
sliders(pidx).Position(1) = (400-sliders(pidx).OuterPosition(3))/2;
else
sliders(pidx) = uislider(self.handles.tabs(j),'Limits',[pstrings(i).Lower pstrings(i).Upper],'Value',pstrings(i).Value,'ValueChangedFcn',@self.valueChangedCallback,'MajorTickLabels',{});
sliders(pidx).ValueChangingFcn = @self.valueChangingCallback;
sliders(pidx).Position(1:3) = [80 ypos 230];
sliders(pidx).MinorTicks = linspace(pstrings(i).Lower,pstrings(i).Upper,21);
sliders(pidx).MajorTicks = linspace(pstrings(i).Lower,pstrings(i).Upper,5);
end
% add labels on the axes
thisstring = pstrings(i).Name;
% for j = length(self.replace_these):-1:1
% this_name = strrep(this_name,self.replace_these{j},self.with_these{j});
% end
if ~pstrings(i).ToggleSwitch
thisstring = [thisstring '= ',strlib.oval(pstrings(i).Value) pstrings(i).Units];
end
controllabel(pidx) = uilabel(self.handles.tabs(j),'Position',[80 ypos+20 230 20],'FontSize',14,'Text',thisstring,'BackgroundColor','w','HorizontalAlignment','center');
if ~pstrings(i).ToggleSwitch
self.handles.lbcontrol(pidx) = uieditfield(self.handles.tabs(j),'numeric','Position',[20 ypos-7 40 20],'Value',pstrings(i).Lower,'ValueChangedFcn',@self.resetSliderBounds,'Tag',pstrings(i).Name,'Limits',[pstrings(i).LowerLimit Inf]);
self.handles.ubcontrol(pidx) = uieditfield(self.handles.tabs(j),'numeric', 'Position',[330 ypos-7 40 20],'Value',pstrings(i).Upper,'ValueChangedFcn',@self.resetSliderBounds,'Tag',pstrings(i).Name,'HorizontalAlignment','left','Limits',[-Inf pstrings(i).UpperLimit ]);
end
ypos = ypos + self.slider_spacing;
end
end
for i = 1:length(self.handles.tabs)
self.handles.tabs(i).BackgroundColor = [1 1 1];
end
self.handles.sliders = sliders;
self.handles.controllabel = controllabel;
drawnow nocallbacks limitrate
warning('on','MATLAB:hg:uicontrol:MinMustBeLessThanMax')
% create a reset button
self.handles.reset = uibutton(fig,'Text','Reset');
self.handles.reset.Position = [150 10 100 20];
self.handles.reset.ButtonPushedFcn = @self.reset;
% remember the original values so we can return to them
self.original_values = self.Pstrings;
|
github
|
stephenslab/mixsqp-paper-master
|
minConf_SPG.m
|
.m
|
mixsqp-paper-master/code/minConf_SPG.m
| 12,576 |
utf_8
|
a320eb6e57068a94152968d150260851
|
function [x, obj, funEvals, projects, timings] = ...
minConf_SPG(funObj, x, funProj, options)
% function [x,f] = minConF_SPG(funObj,x,funProj,options)
%
% Function for using Spectral Projected Gradient to solve problems of the form
% min funObj(x) s.t. x in C
%
% @funObj(x): function to minimize (returns gradient as second argument)
% @funProj(x): function that returns projection of x onto C
%
% options:
% verbose: level of verbosity (0: no output, 1: final, 2: iter (default), 3:
% debug)
% optTol: tolerance used to check for optimality (default: 1e-5)
% progTol: tolerance used to check for lack of progress (default: 1e-9)
% maxIter: maximum number of calls to funObj (default: 500)
% numDiff: compute derivatives numerically (0: use user-supplied
% derivatives (default), 1: use finite differences, 2: use complex
% differentials)
% suffDec: sufficient decrease parameter in Armijo condition (default
% : 1e-4)
% interp: type of interpolation (0: step-size halving, 1: quadratic,
% 2: cubic)
% memory: number of steps to look back in non-monotone Armijo
% condition
% useSpectral: use spectral scaling of gradient direction (default:
% 1)
% curvilinear: backtrack along projection Arc (default: 0)
% testOpt: test optimality condition (default: 1)
% feasibleInit: if 1, then the initial point is assumed to be
% feasible
% bbType: type of Barzilai Borwein step (default: 1)
%
% Notes:
% - if the projection is expensive to compute, you can reduce the
% number of projections by setting testOpt to 0
nVars = length(x);
% Set Parameters
if nargin < 4
options = [];
end
[verbose,numDiff,optTol,progTol,maxIter,suffDec,interp,memory,useSpectral,curvilinear,feasibleInit,testOpt,bbType] = ...
myProcessOptions(...
options,'verbose',2,'numDiff',0,'optTol',1e-5,'progTol',1e-9,'maxIter',500,'suffDec',1e-4,...
'interp',2,'memory',10,'useSpectral',1,'curvilinear',0,'feasibleInit',0,...
'testOpt',1,'bbType',1);
% Output Log
if verbose >= 2
if testOpt
fprintf('%10s %10s %10s %15s %15s %14s\n','Iteration','FunEvals','Projections','Step Length','Function Val','Opt Cond');
else
fprintf('%10s %10s %10s %15s %15s\n','Iteration','FunEvals','Projections','Step Length','Function Val');
end
end
% Make objective function (if using numerical derivatives)
funEvalMultiplier = 1;
if numDiff
if numDiff == 2
useComplex = 1;
else
useComplex = 0;
end
funObj = @(x)autoGrad(x,useComplex,funObj);
funEvalMultiplier = nVars+1-useComplex;
end
% Evaluate Initial Point
if ~feasibleInit
x = funProj(x);
end
[f,g] = funObj(x);
projects = 1;
funEvals = 1;
obj = zeros(maxIter,1);
timings = zeros(maxIter,1);
% Optionally check optimality
if testOpt
projects = projects+1;
if max(abs(funProj(x-g)-x)) < optTol
if verbose >= 1
fprintf('First-Order Optimality Conditions Below optTol at Initial Point\n');
end
return;
end
end
i = 1;
while funEvals <= maxIter
tic;
% Compute Step Direction
if i == 1 || ~useSpectral
alpha = 1;
else
y = g-g_old;
s = x-x_old;
if bbType == 1
alpha = (s'*s)/(s'*y);
else
alpha = (s'*y)/(y'*y);
end
if alpha <= 1e-10 || alpha > 1e10
alpha = 1;
end
end
d = -alpha*g;
f_old = f;
x_old = x;
g_old = g;
% Compute Projected Step
if ~curvilinear
d0 = d;
d = funProj(x + d0) - x;
projects = projects+1;
end
% Check that Progress can be made along the direction
gtd = g'*d;
% Select Initial Guess to step length
if i == 1
t = min(1,1/sum(abs(g)));
else
t = 1;
end
% Compute reference function for non-monotone condition
if memory == 1
funRef = f;
else
if i == 1
old_fvals = repmat(-inf,[memory 1]);
end
if i <= memory
old_fvals(i) = f;
else
old_fvals = [old_fvals(2:end);f];
end
funRef = max(old_fvals);
end
% Evaluate the Objective and Gradient at the Initial Step
if curvilinear
x_new = funProj(x + t*d);
projects = projects+1;
else
x_new = x + t*d;
end
[f_new,g_new] = funObj(x_new);
funEvals = funEvals+1;
% Backtracking Line Search
lineSearchIters = 1;
while f_new > funRef + suffDec*g'*(x_new-x) || ~isLegal(f_new)
temp = t;
if interp == 0 || ~isLegal(f_new)
if verbose == 3
fprintf('Halving Step Size\n');
end
t = t/2;
elseif interp == 2 && isLegal(g_new)
if verbose == 3
fprintf('Cubic Backtracking\n');
end
t = polyinterp([0 f gtd; t f_new g_new'*d]);
elseif lineSearchIters < 2 || ~isLegal(f_prev)
if verbose == 3
fprintf('Quadratic Backtracking\n');
end
t = polyinterp([0 f gtd; t f_new sqrt(-1)]);
else
if verbose == 3
fprintf('Cubic Backtracking on Function Values\n');
end
t = polyinterp([0 f gtd; t f_new sqrt(-1);t_prev f_prev sqrt(-1)]);
end
% Adjust if change is too small
if t < temp*1e-3
if verbose == 3
fprintf('Interpolated value too small, Adjusting\n');
end
t = temp*1e-3;
elseif t > temp*0.6
if verbose == 3
fprintf('Interpolated value too large, Adjusting\n');
end
t = temp*0.6;
end
% Check whether step has become too small
if max(abs(t*d)) < progTol || t == 0
if verbose == 3
fprintf('Line Search failed\n');
end
t = 0;
f_new = f;
g_new = g;
break;
end
% Evaluate New Point
f_prev = f_new;
t_prev = temp;
if curvilinear
x_new = funProj(x + t*d);
projects = projects+1;
else
x_new = x + t*d;
end
[f_new,g_new] = funObj(x_new);
funEvals = funEvals+1;
lineSearchIters = lineSearchIters+1;
end
% Take Step
x = x_new;
f = f_new;
g = g_new;
if testOpt
optCond = max(abs(funProj(x-g)-x));
projects = projects+1;
end
% Output Log
if verbose >= 2
if testOpt
fprintf('%10d %10d %10d %15.5e %15.9e %14.8e\n',i,funEvals*funEvalMultiplier,projects,t,f,optCond);
else
fprintf('%10d %10d %10d %15.5e %15.5e\n',i,funEvals*funEvalMultiplier,projects,t,f);
end
end
% Check optimality
if testOpt
if optCond < optTol
if verbose >= 1
fprintf('First-Order Optimality Conditions Below optTol\n');
end
break;
end
end
if funEvals*funEvalMultiplier > maxIter
if verbose >= 1
fprintf('Function Evaluations exceeds maxIter\n');
end
break;
end
obj(i) = f;
timings(i) = toc;
i = i + 1;
end
obj = obj(1:(i-1));
timings = timings(1:(i-1));
end
% ----------------------------------------------------------------------------
function [minPos,fmin] = polyinterp(points,doPlot,xminBound,xmaxBound)
% function [minPos] = polyinterp(points,doPlot,xminBound,xmaxBound)
%
% Minimum of interpolating polynomial based on function and derivative
% values
%
% In can also be used for extrapolation if {xmin,xmax} are outside
% the domain of the points.
%
% Input:
% points(pointNum,[x f g])
% doPlot: set to 1 to plot, default: 0
% xmin: min value that brackets minimum (default: min of points)
% xmax: max value that brackets maximum (default: max of points)
%
% set f or g to sqrt(-1) if they are not known
% the order of the polynomial is the number of known f and g values minus 1
if nargin < 2
doPlot = 0;
end
nPoints = size(points,1);
order = sum(sum((imag(points(:,2:3))==0)))-1;
% Code for most common case:
% - cubic interpolation of 2 points
% w/ function and derivative values for both
% - no xminBound/xmaxBound
if nPoints == 2 && order ==3 && nargin <= 2 && doPlot == 0
% Solution in this case (where x2 is the farthest point):
% d1 = g1 + g2 - 3*(f1-f2)/(x1-x2);
% d2 = sqrt(d1^2 - g1*g2);
% minPos = x2 - (x2 - x1)*((g2 + d2 - d1)/(g2 - g1 + 2*d2));
% t_new = min(max(minPos,x1),x2);
[minVal minPos] = min(points(:,1));
notMinPos = -minPos+3;
d1 = points(minPos,3) + points(notMinPos,3) - 3*(points(minPos,2)-points(notMinPos,2))/(points(minPos,1)-points(notMinPos,1));
d2 = sqrt(d1^2 - points(minPos,3)*points(notMinPos,3));
if isreal(d2)
t = points(notMinPos,1) - (points(notMinPos,1) - points(minPos,1))*((points(notMinPos,3) + d2 - d1)/(points(notMinPos,3) - points(minPos,3) + 2*d2));
minPos = min(max(t,points(minPos,1)),points(notMinPos,1));
else
minPos = mean(points(:,1));
end
return;
end
xmin = min(points(:,1));
xmax = max(points(:,1));
% Compute Bounds of Interpolation Area
if nargin < 3
xminBound = xmin;
end
if nargin < 4
xmaxBound = xmax;
end
% Constraints Based on available Function Values
A = zeros(0,order+1);
b = zeros(0,1);
for i = 1:nPoints
if imag(points(i,2))==0
constraint = zeros(1,order+1);
for j = order:-1:0
constraint(order-j+1) = points(i,1)^j;
end
A = [A;constraint];
b = [b;points(i,2)];
end
end
% Constraints based on available Derivatives
for i = 1:nPoints
if isreal(points(i,3))
constraint = zeros(1,order+1);
for j = 1:order
constraint(j) = (order-j+1)*points(i,1)^(order-j);
end
A = [A;constraint];
b = [b;points(i,3)];
end
end
% Find interpolating polynomial
params = A\b;
% Compute Critical Points
dParams = zeros(order,1);
for i = 1:length(params)-1
dParams(i) = params(i)*(order-i+1);
end
if any(isinf(dParams))
cp = [xminBound;xmaxBound;points(:,1)].';
else
cp = [xminBound;xmaxBound;points(:,1);roots(dParams)].';
end
% Test Critical Points
fmin = inf;
minPos = (xminBound+xmaxBound)/2; % Default to Bisection if no critical points valid
for xCP = cp
if imag(xCP)==0 && xCP >= xminBound && xCP <= xmaxBound
fCP = polyval(params,xCP);
if imag(fCP)==0 && fCP < fmin
minPos = real(xCP);
fmin = real(fCP);
end
end
end
% Plot Situation
if doPlot
figure(1); clf; hold on;
% Plot Points
plot(points(:,1),points(:,2),'b*');
% Plot Derivatives
for i = 1:nPoints
if isreal(points(i,3))
m = points(i,3);
b = points(i,2) - m*points(i,1);
plot([points(i,1)-.05 points(i,1)+.05],...
[(points(i,1)-.05)*m+b (points(i,1)+.05)*m+b],'c.-');
end
end
% Plot Function
x = min(xmin,xminBound)-.1:(max(xmax,xmaxBound)+.1-min(xmin,xminBound)-.1)/100:max(xmax,xmaxBound)+.1;
size(x)
for i = 1:length(x)
f(i) = polyval(params,x(i));
end
plot(x,f,'y');
axis([x(1)-.1 x(end)+.1 min(f)-.1 max(f)+.1]);
% Plot Minimum
plot(minPos,fmin,'g+');
if doPlot == 1
pause(1);
end
end
end
% ----------------------------------------------------------------------------
function [legal] = isLegal(v)
legal = sum(any(imag(v(:))))==0 & sum(isnan(v(:)))==0 & sum(isinf(v(:)))==0;
end
% ----------------------------------------------------------------------------
function [varargout] = myProcessOptions(options,varargin)
% Similar to processOptions, but case insensitive and
% using a struct instead of a variable length list
options = toUpper(options);
for i = 1:2:length(varargin)
if isfield(options,upper(varargin{i}))
v = getfield(options,upper(varargin{i}));
if isempty(v)
varargout{(i+1)/2}=varargin{i+1};
else
varargout{(i+1)/2}=v;
end
else
varargout{(i+1)/2}=varargin{i+1};
end
end
end
% ----------------------------------------------------------------------------
function [o] = toUpper(o)
if ~isempty(o)
fn = fieldnames(o);
for i = 1:length(fn)
o = setfield(o,upper(fn{i}),getfield(o,fn{i}));
end
end
end
|
github
|
stephenslab/mixsqp-paper-master
|
mixobj.m
|
.m
|
mixsqp-paper-master/code/mixobj.m
| 291 |
utf_8
|
7b74c7f79fcc58d369c351aca993583a
|
% Compute the objective, and gradient of this objective, optimized by
% mix-SQP.
function [f, g] = mixobj (L, x, e)
m = numel(x);
y = L*x + e;
if any(y <= 0)
f = Inf;
g = zeros(m,1);
else
n = size(L,1);
f = -sum(log(y));
d = 1./(y + e);
g = -(d'*L)';
end
|
github
|
kuhu12/BreastCancerDetection-master
|
Binary_Genetic_Algorithm_original.m
|
.m
|
BreastCancerDetection-master/Neural Networks/Binary_Genetic_Algorithm_original.m
| 3,000 |
utf_8
|
6dd871e2d5c9bb857a256490e67e7e66
|
function Feat_Index = Binary_Genetic_Algorithm_original(X1,Y1)
% Written by BABATUNDE Oluleye H, PhD Student
% Address: eAgriculture Research Group, School of Computer and Security
% Science, Edith Cowan University, Mt Lawley, 6050, WA, Australia
% Date: 2013
% Please cite any of the article below (if you use the code), thank you
% "BABATUNDE Oluleye, ARMSTRONG Leisa J, LENG Jinsong and DIEPEVEEN Dean (2014).
% Zernike Moments and Genetic Algorithm: Tutorial and APPLICATION.
% British Journal of Mathematics & Computer Science.
% 4(15):2217-2236."
%%% OR
%BABATUNDE, Oluleye and ARMSTRONG, Leisa and LENG, Jinsong and DIEPEVEEN (2014).
% A Genetic Algorithm-Based Feature Selection. International Journal
%of Electronics Communication and Computer Engineering: 5(4);889--905.
% DataSet here
%Ionosphere dataset from the UCI machine learning repository:
%http://archive.ics.uci.edu/ml/datasets/Ionosphere
%X is a 351x34 real-valued matrix of predictors. Y is a categorical response:
%"b" for bad radar returns and "g" for good radar returns.
% NOTE: You can run this code directory on your PC as the dataset is
% available in MATLAB software
global a b
a=X1;
b=Y1;
% load ionosphere.mat % This contains X (Features field) and Y (Class Information)
% This is available in Mathworks
GenomeLength =9; % This is the number of features in the dataset
tournamentSize = 2;
%options= gaoptimset(@PopFunction);
% options = gaoptimset('CreationFcn', {@PopFunction},...
% 'PopulationSize',50,...
% 'Generations',100,...
% 'PopulationType', 'bitstring',...
% 'SelectionFcn',{@selectiontournament,tournamentSize},...
% 'MutationFcn',{@mutationuniform, 0.1},...
% 'CrossoverFcn', {@crossoverarithmetic,0.8},...
% 'EliteCount',2,...
% 'StallGenLimit',100,...
% 'PlotFcns',{@gaplotbestf},...
% 'Display', 'iter');
rand('seed',1)
nVars = 9; %
FitnessFcn = @FitFunc_KNN;
chromosome = ga(FitnessFcn,nVars);
Best_chromosome = chromosome; % Best Chromosome
Feat_Index = find(Best_chromosome==1); % Index of Chromosome
end
%%% POPULATION FUNCTION
function [pop] = PopFunction(GenomeLength,~,options)
RD = rand;
pop = (rand(options.PopulationSize, GenomeLength)> RD); % Initial Population
end
%%% FITNESS FUNCTION You may design your own fitness function here
function [FitVal] = FitFunc_KNN(pop)
global a b
FeatIndex = find(pop==1); %Feature Index
a1 = a;% Features Set
b1 = grp2idx(b);% Class Information
a1 = a1(:,[FeatIndex]);
NumFeat = numel(FeatIndex);
Compute = ClassificationKNN.fit(a1,b1,'NSMethod','exhaustive','Distance','euclidean');
Compute.NumNeighbors = 3; % kNN = 3
FitVal = resubLoss(Compute)/(9-NumFeat);
end
|
github
|
burakbayramli/dersblog-master
|
rcs2.m
|
.m
|
dersblog-master/compscieng/compscieng_app20cfit2/rcspline/code/rcs2.m
| 802 |
utf_8
|
84d15ceabde2f057b078f701a961d605
|
function [bhat X]=rcs2(x,y,knots,plots)
n=length(y);
k=knots;
X1=x;
q=length(k);
myX=zeros(n,length(knots)-2);
for j=1:(q-2)
XX=(x-k(j)).^3.*(x>k(j))-(x-k(q-1)).^3.*(x>k(q-1)).*(k(q)-k(j))./(k(q)-k(q-1));
XX=XX+(x-k(q)).^3.*(x>k(q)).*(k(q-1)-k(j))./(k(q)-k(q-1));
myX(:,j)=XX;
end
X=[ones(n,1) X1 myX]; %the design matrix
bhat=X\y; %obtain the coefs
%Deal with the restriction and derive the last coefs so as linearity is
%imposed beyond the first and the last knots:
bhatt(length(bhat)+1)=sum(bhat(3:end).*(k(1:end-2)-k(end))');
bhatt(length(bhat)+1)=bhatt(length(bhat)+1)./(k(end)-k(end-1));
bhatt=[bhatt 0];
bhatt(end)=sum(bhat(3:end).*(k(1:end-2)-k(end-1))');
bhatt(end)=bhatt(end)./(k(end-1)-k(end));
bhat=[bhat; bhatt(end-1:end)'];
end
|
github
|
burakbayramli/dersblog-master
|
rcs.m
|
.m
|
dersblog-master/compscieng/compscieng_app20cfit2/rcspline/code/rcs.m
| 3,123 |
utf_8
|
9fadf94545203f04e3c43efa7a4c69fa
|
function [bhat ff sse X]=rcs(x,y,knots,plots)
%INTERIOR FUNCTION FOR THE rcspline function:
%Fits a restricted cubic spline via least squares.
%The obtained spline is linear beyond the first and the last knot. The
%power basis representation is used. That is, the fitted spline is of the
%form: f(x)=b0+b1*x+b2*(x-t1)^3*(x>t1)+b3*(x-t2)^3*(x>t2)+...
%where t1 t2,... are the desired knots. For more information see also
%Harrell Jr, Regression Modelling Strategies.
%
%INPUT ARGUMENTS:
%x: A vector containing the covariate values x.
%y: A vector of length(x) that contains the response values y.
%knots: A vector of points at which the knots are to be placed.
%
%OPTIONAL INPUT ARGUMENT:
%plots: If set to 1, it returns a plot of the spline and the data.
%Otherwise it is ignored. This input argument can also not be reached at
%all.
%
%OUTPUT ARGUMENTS:
%bhat: the estimated spline coefficients.
%ff: a function handle from which you can evaluate the spline value at a
% given x (which can be a scalar or a vector). For example ff(2) will
% yield the spline value for x=2. You can use a vector (grid) of x values to
% plot the f(x) by requesting plot(x,f(x)).
%rss: equals to sum((y-ff(x)).^2)
%Code author: Leonidas E. Bantis, University of the Aegean.
%E-mail: [email protected]
%Date: January 14th, 2013.
%Version: 1.
%Some error checking:
% if sum(isnan(x))~=0 || sum(isnan(y))~=0;error('The x and y vectors must not contain NaNs');end
% [rx cx]=size(x);
% [ry cy]=size(y);
% if rx~=1 && cx~=1;error('x must be a vector and not a matrix');end
% if ry~=1 && cy~=1;error('x must be a vector and not a matrix');end
% if cx~=1;x=x';end
% if cy~=1;y=y';end
% if length(x)~=length(y);error('x and y must have the same length');end
%
% [rk ck]=size(knots);
% if rk~=1 && ck~=1;error('knots must be a vector and not a matrix');end
n=length(y);
k=knots;
X1=x;
q=length(k);
myX=zeros(n,length(knots)-2);
for j=1:(q-2)
XX=(x-k(j)).^3.*(x>k(j))-(x-k(q-1)).^3.*(x>k(q-1)).*(k(q)-k(j))./(k(q)-k(q-1));
XX=XX+(x-k(q)).^3.*(x>k(q)).*(k(q-1)-k(j))./(k(q)-k(q-1));
myX(:,j)=XX;
end
X=[ones(n,1) X1 myX]; %the design matrix
bhat=X\y; %obtain the coefs
%Deal with the restriction and derive the last coefs so as linearity is
%imposed beyond the first and the last knots:
bhatt(length(bhat)+1)=sum(bhat(3:end).*(k(1:end-2)-k(end))');
bhatt(length(bhat)+1)=bhatt(length(bhat)+1)./(k(end)-k(end-1));
bhatt=[bhatt 0];
bhatt(end)=sum(bhat(3:end).*(k(1:end-2)-k(end-1))');
bhatt(end)=bhatt(end)./(k(end-1)-k(end));
bhat=[bhat; bhatt(end-1:end)'];
%Just obtained the estimated coefs vector
f2=@(x) bhat(1)+bhat(2).*x+sum(bhat(3:end)'.*(x-k(1:end)).^3.*(x>k(1:end)));
gr=min(x):0.01:max(x);
ff=@(x)arrayfun(f2, x); %The spline function handle
%If requested provide the plot:
if plots==1;
%subplot(2,1,1)
plot(x,y,'.')
hold on;
plot(knots,min(y)+zeros(1,length(knots)),'or')
plot(gr,ff(gr),'r');
legend('data','knots','spline')
end
sse=sum((y-ff(x)).^2);
end
|
github
|
burakbayramli/dersblog-master
|
rcs3.m
|
.m
|
dersblog-master/compscieng/compscieng_app20cfit2/rcspline/code/rcs3.m
| 878 |
utf_8
|
7b83b1f01951e48c1d9e2d0b281c3abd
|
function [bhat X]=rcs3(x,y,knots)
n=length(y);
k=knots;
X1=x;
q=length(k);
myX=zeros(n,length(knots)-2);
for j=1:(q-2)
tmp1 = (x-k(j)).^3.*(x>k(j));
tmp2 = (x-k(q-1)).^3.*(x>k(q-1)).*(k(q)-k(j));
XX= tmp1-tmp2./(k(q)-k(q-1));
tmp1 = (x-k(q)).^3.*(x>k(q));
tmp2 = (k(q-1)-k(j));
XX=XX+tmp1.*tmp2./(k(q)-k(q-1));
myX(:,j)=XX;
end
X=[ones(n,1) X1 myX]; %the design matrix
bhat=X\y; %obtain the coefs
%Deal with the restriction and derive the last coefs so as linearity is
%imposed beyond the first and the last knots:
bhatt(length(bhat)+1)=sum(bhat(3:end).*(k(1:end-2)-k(end))');
bhatt(length(bhat)+1)=bhatt(length(bhat)+1)./(k(end)-k(end-1));
bhatt=[bhatt 0];
bhatt(end)=sum(bhat(3:end).*(k(1:end-2)-k(end-1))');
bhatt(end)=bhatt(end)./(k(end-1)-k(end));
disp(bhatt(end-1:end));
bhat=[bhat; bhatt(end-1:end)'];
end
|
github
|
burakbayramli/dersblog-master
|
rcspline.m
|
.m
|
dersblog-master/compscieng/compscieng_app20cfit2/rcspline/code/rcspline.m
| 7,637 |
utf_8
|
e6f8dd883bbf019f75d9df641bd87bb5
|
function [bhat f sse knots CI]=rcspline(x,y,knots,bootsams,atwhich,plots)
%Fits the so called restricted cubic spline via least squares (see Harrell
%(2001)). The obtained spline is linear beyond the first and the last
%knot. The truncated power basis representation is used. That is, the
%fitted spline is of the form:
%f(x)=b0+b1*x+b2*(x-t1)^3*(x>t1)+b3*(x-t2)^3*(x>t2)+...
%where t1 t2,... are the desired knots.
%95% confidence intervals are provided based on the bootstrap procedure.
%For more information see also:
%Frank E Harrell Jr, Regression Modelling Strategies (With application to
%linear models, logistic regression and survival analysis), 2001,
%Springer Series in Statistics, pages 20-21.
%
%INPUT ARGUMENTS:
%x: A vector containing the covariate values x.
%y: A vector of length(x) that contains the response values y.
%knots: A vector of points at which the knots are to be placed.
% Alternatively, it can be set as 'prc3', 'prc4', ..., 'prc8' and 3
% or 4 or...8 knots placed at equally spaced percentiles will be used.
% It can also be set to 'eq3', 'eq4', ...,'eq8' to use 3 or 4 or ...
% or 8 equally spaced knots. There is a difference in using one of
% these strings to define the knots instead of passing them directly
% as a vector of numbers and the difference involves only the
% bootstrap option and not the fit itself. When the bootstrap is used
% and the knots are passed in as numbers, then the knot sequence will
% be considered fixed as provided by the user for each bootstrap
% iteration. If a string as the ones mentioned above is used, then
% the knot sequence is re-evaluated for each bootstrap sample
% based on this choice.
%
%OPTIONAL INPUT ARGUMENTS: (These can be not reached at all or set as [] to
%proceed to the next optional input argument):
%
%bootsams: The number of bootstrap samples if the user wants to derive 95% CIs.
%atwhich: a vector of x values at which the CIs of the f(x) are to be evaluated.
%plots: If set to 1, it returns a plot of the spline and the data.
% Otherwise it is ignored. This input argument can also not be reached
% at all. (It also plots the CIs provided that they are requested).
%
%OUTPUT ARGUMENTS:
%bhat: the estimated spline coefficients.
%f: a function handle from which you can evaluate the spline value at a
% given x (which can be a scalar or a vector). For example ff(2) will
% yield the spline value for x=2. You can use a vector (grid) of x values to
% plot the f(x) by requesting plot(x,f(x)).
%sse: equals to sum((y-ff(x)).^2)
%knots: the knots used for fitting the spline.
%CI : 95% bootstrap based confidence intervals.
% Obtained only if the bootstrap is requested and and only fot the
% points at which the CIs were requested. Hence, CI is a three column
% matrix with its first column be the spline value at the points
% supplied by the user, and the second and third column are
% respectively the lower and upper CI limits for that points.
%
%References: Frank E. Harrell, Jr. Regression Modeling Strategies (With
%applications to linear models, logistic regression, and survival
%analysis). Springer 2001.
%
%
%Code author: Leonidas E. Bantis,
%Dept. of Statistics & Actuarial-Financial Mathematics, School of Sciences
%University of the Aegean, Samos Island.
%
%E-mail: [email protected]
%Date: January 14th, 2013.
%Version: 1.
%Some error checking:
if sum(isnan(x))~=0 || sum(isnan(y))~=0;error('The x and y vectors must not contain NaNs');end
[rx cx]=size(x);
[ry cy]=size(y);
if rx~=1 && cx~=1;error('x must be a vector and not a matrix');end
if ry~=1 && cy~=1;error('x must be a vector and not a matrix');end
if cx~=1;x=x';end
if cy~=1;y=y';end
if length(x)~=length(y);error('x and y must have the same length');end
if isnumeric(knots)==1
[rk ck]=size(knots);
if rk~=1 && ck~=1;error('knots must be a vector and not a matrix');end
end
if nargin>=4 && nargin<5
error('The number of bootstrap samples must be followed by the points at which the CIs are needed');
end
if nargin>=5
if isempty(bootsams)==1 && isempty(bootsams)~=1;error('If the ''bootsams'' is empty then the ''atwhich'' must be also empty');end
if isempty(bootsams)~=1 && isempty(bootsams)==1;error('If the ''atwhwich'' is empty then the ''bootsams'' must be also empty');end
end
orknots=knots; %original knots suuplied by the user
if nargin>=5;
[rat cat]=size(y);
if rat~=1 && cat~=1;error('x must be a vector and not a matrix');end
if cat~=1;atwhich=atwhich';end
end
if strcmpi(knots, 'prc3')==1
knots=prctile(x,linspace(0,100,3));
elseif strcmpi(knots, 'prc4')==1
knots=prctile(x,linspace(0,100,4));
elseif strcmpi(knots, 'prc5')==1
knots=prctile(x,linspace(0,100,5));
elseif strcmpi(knots, 'prc6')==1
knots=prctile(x,linspace(0,100,6));
elseif strcmpi(knots, 'prc7')==1
knots=prctile(x,linspace(0,100,7));
elseif strcmpi(knots, 'prc8')==1
knots=prctile(x,linspace(0,100,8));
elseif strcmpi(knots, 'eq3')==1
knots=linspace(min(x),max(x),3);
elseif strcmpi(knots, 'eq4')==1
knots=linspace(min(x),max(x),4);
elseif strcmpi(knots, 'eq5')==1
knots=linspace(min(x),max(x),5);
elseif strcmpi(knots, 'eq6')==1
knots=linspace(min(x),max(x),6);
elseif strcmpi(knots, 'eq7')==1
knots=linspace(min(x),max(x),7);
elseif strcmpi(knots, 'eq8')==1
knots=linspace(min(x),max(x),8);
end
n=length(y);
if nargin<6;plots=0;end
[bhat f sse]=rcs(x,y,knots,plots);%get the spline
if nargin>=4 && isempty(bootsams)~=1
FF=zeros(length(atwhich),bootsams);
for boots=1:bootsams
at=randsample(n,n,'true');
xb=x(at);yb=y(at);
if isnumeric(knots)~=0;
bknots=evknots(orknots,xb);
else
bknots=knots;
end
[~, fb]=rcs(xb,yb,bknots,0);
FF(:,boots)=fb(atwhich);
end
low=zeros(1,length(atwhich));
upp=low;
for i=1:length(atwhich)
low(i)=prctile(FF(i,:),2.5);
upp(i)=prctile(FF(i,:),97.5);
end
low=low';upp=upp';
CI=[atwhich' f(atwhich)' low upp];
if plots==1
%subplot(2,1,2)
figure
gr=min(x):0.01:max(x);
plot(gr,f(gr),'r');hold on;
plot(atwhich,low,'.g');plot(atwhich,upp,'.g');
legend('spline', '95% CIs')
hold off
end
end
end
function out=evknots(knots,x)
%interior function that evaluates the knots for the bootstrap
%when they are not consider fixed.
if strcmpi(knots, 'prc3')==1
knots=prctile(x,linspace(0,100,3));
elseif strcmpi(knots, 'prc4')==1
knots=prctile(x,linspace(0,100,4));
elseif strcmpi(knots, 'prc5')==1
knots=prctile(x,linspace(0,100,5));
elseif strcmpi(knots, 'prc6')==1
knots=prctile(x,linspace(0,100,6));
elseif strcmpi(knots, 'prc7')==1
knots=prctile(x,linspace(0,100,7));
elseif strcmpi(knots, 'prc8')==1
knots=prctile(x,linspace(0,100,8));
elseif strcmpi(knots, 'eq3')==1
knots=linspace(min(x),max(x),3);
elseif strcmpi(knots, 'eq4')==1
knots=linspace(min(x),max(x),4);
elseif strcmpi(knots, 'eq5')==1
knots=linspace(min(x),max(x),5);
elseif strcmpi(knots, 'eq6')==1
knots=linspace(min(x),max(x),6);
elseif strcmpi(knots, 'eq7')==1
knots=linspace(min(x),max(x),7);
elseif strcmpi(knots, 'eq8')==1
knots=linspace(min(x),max(x),8);
end
out=knots;
end
|
github
|
burakbayramli/dersblog-master
|
minsky_III_dx.m
|
.m
|
dersblog-master/chaos/chaos_app02/minsky_III_dx.m
| 1,328 |
utf_8
|
f7e326cfb498912ac92b72172a5e9633
|
% This code was written as a part of Reseacrh Methods MSc course
% Coded by: Piotr Z. Jelonek, e-mail: [email protected],
% 22nd February 2016
%
% Disclaimer:
% 1. This script is intended for a non-commercial use.
% 2. You can use, amend and edit it to fit to your purposes for your own use only,
% but not for further distribution.
% 3. This script comes with no warranty.
% 4. Please quote the author when using the script.
%
% Copyright: The author(s) own the right to modify or amend the script and
% claim for the authorship of it.
function dx = minsky_III_dx(tspan,x,params)
alpha=params(1); beta=params(2); delta=params(3); nu=params(4);
r_b=params(5); s=params(6); tau_p=params(7); tau_i=params(8);
x_i=params(9); y_i=params(10); s_i=params(11); m_i=params(12);
x_w=params(13); y_w=params(14); s_w=params(15); m_w=params(16);
r=r_b; % <- interest rate
if x(4)>0
r=r+x(4);
end
p=1-x(2)-r*x(3);
f=-(1/tau_p)*(1-x(2)/(1-s));
I=(y_i-m_i)*exp(s_i*((p/nu)-x_i)/(y_i-m_i))+m_i;
W=(y_w-m_w)*exp(s_w*(x(1)-x_w)/(y_w-m_w))+m_w;
dx=zeros(4,1);
dx(1)=( ((1/nu)*I-delta) -(alpha + beta) )*x(1);
dx(2)=( W - (alpha+f) )*x(2);
dx(3)=( I-p ) -( (1/nu)*I - delta + f )*x(3);
dx(4)=-(1/tau_i)*(x(4)-f);
end
|
github
|
burakbayramli/dersblog-master
|
minsky_II_dx.m
|
.m
|
dersblog-master/chaos/chaos_app02/minsky_II_dx.m
| 1,510 |
utf_8
|
f13e0e8b8f3c81bef08fcfd6be545a7e
|
% This code was written as a part of Reseacrh Methods MSc course
% Coded by: Piotr Z. Jelonek, e-mail: [email protected],
% 20th February 2016
%
% Disclaimer:
% 1. This script is intended for a non-commercial use.
% 2. You can use, amend and edit it to fit to your purposes for your own use only,
% but not for further distribution.
% 3. This script comes with no warranty.
% 4. Please quote the author when using the script.
%
% Copyright: The author(s) own the right to modify or amend the script and
% claim for the authorship of it.
function dx = minsky_II_dx(tspan,x,params)
% reading paramaters
alpha=params(1); beta=params(2); gamma=params(3); nu=params(4); r=params(5);
x_p=params(6); y_p=params(7); s_p=params(8); m_p=params(9);
x_l=params(10); y_l=params(11); s_l=params(12); m_l=params(13);
% auxilaries
L=x(1)/x(4); % <- labour
P=x(1)-x(2)*L - r*x(3); % <- profit
p=P/(nu*x(1)); % <- profit to capital
I=(y_p-m_p)*exp(s_p*(p-x_p)/(y_p-m_p))+m_p; % <- investment as a function of profit
l=x(1)/(x(4)*x(5)); % <- employment rate
H=(y_l-m_l)*exp(s_l*(l-x_l)/(y_l-m_l))+m_l; % <- growth rate of wages as a fctn. of employment rate
% derivative
dx=zeros(5,1);
dx(1)=x(1)*(I/nu - gamma );
dx(2)=H*x(2);
dx(3)=I*x(1)-P;
dx(4)=alpha*x(4);
dx(5)=beta*x(5);
end
|
github
|
burakbayramli/dersblog-master
|
Arenstorf.m
|
.m
|
dersblog-master/chaos/chaos_app01/Arenstorf.m
| 323 |
utf_8
|
5c28f737e58b0fe1a1b313e027acaaf7
|
% Gander, {\em Scientific Computing An Introduction using Maple and MATLAB}
% pg 618
function yp=Arenstorf(t,y);
a=0.012277471; b=1-a;
D1=((y(1)+a)^2+y(2)^2)^(3/2);
D2=((y(1)-b)^2+y(2)^2)^(3/2);
yp(1,1)=y(3);
yp(2,1)=y(4);
yp(3,1)=y(1)+2*y(4)-b*(y(1)+a)/D1-a*(y(1)-b)/D2;
yp(4,1)=y(2)-2*y(3)-b*y(2)/D1-a*y(2)/D2;
yp=yp(:);
|
github
|
burakbayramli/dersblog-master
|
subgrad_func.m
|
.m
|
dersblog-master/func_analysis/func_42_subgrad/octave/subgrad_func.m
| 597 |
utf_8
|
8d6a2d708538f2955ccfcc6728af2add
|
% https://raw.githubusercontent.com/fengcls/Lasso/master/lasso_main.m
% 0.5*||Ax - b||_2 + lambda*||x||_1
% subgradient method
function subgrad_func(A,b,lambda)
[~,n2] = size(A);
x = zeros(n2,1);
k=1;
g = ones(n2,1);
t = 0.01;
while k<3 || abs(f(k-1)-f(k-2))/f(k-1)>1e-5
% f(round(k/10)+1)=0.5*norm(A*x-b,2)^2+lambda*norm(x,1);
f(k)=0.5*norm(A*x-b,2)^2+lambda*norm(x,1);
disp(f(k));
% the subgradient is A'*(A*x-b)
s = x;
s(x>0)=1;
s(x<0)=-1;
s(x==0) = -2*rand(length(find(x==0)),1)+1;
g = A'*(A*x-b)+lambda*s;
x = x - t*g;
k = k+1;
end;
x
|
github
|
burakbayramli/dersblog-master
|
addblock_svd_update2.m
|
.m
|
dersblog-master/linear/linear_29/matlab/addblock_svd_update2.m
| 754 |
utf_8
|
ade811810150881725a00f947bf13b82
|
% kolon ekini satir ekine cevir
function [Up1,Sp,Vp1] = addblock_svd_update2( Uarg, Sarg, Varg, Aarg, force_orth )
U = Varg;
V = Uarg;
S = Sarg;
A = Aarg';
current_rank = size( U, 2 );
m = U' * A;
p = A - U*m;
P = orth( p );
P = [ P zeros(size(P,1), size(p,2)-size(P,2)) ];
Ra = P' * p;
z = zeros( size(m) );
K = [ S m ; z' Ra ];
[tUp,tSp,tVp] = svds( K, current_rank );
Sp = tSp;
Up = [ U P ] * tUp;
Vp = V * tVp( 1:current_rank, : );
Vp = [ Vp ; tVp( current_rank+1:size(tVp,1), : ) ];
if ( force_orth )
[UQ,UR] = qr( Up, 0 );
[VQ,VR] = qr( Vp, 0 );
[tUp,tSp,tVp] = svds( UR * Sp * VR', current_rank );
Up = UQ * tUp;
Vp = VQ * tVp;
Sp = tSp;
end;
Up1 = Vp;
Vp1 = Up;
return;
|
github
|
b-xiang/webrtc-master
|
readDetection.m
|
.m
|
webrtc-master/modules/audio_processing/transient/test/readDetection.m
| 927 |
utf_8
|
f6af5020971d028a50a4d19a31b33bcb
|
%
% Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [d, t] = readDetection(file, fs, chunkSize)
%[d, t] = readDetection(file, fs, chunkSize)
%
%Reads a detection signal from a DAT file.
%
%d: The detection signal.
%t: The respective time vector.
%
%file: The DAT file where the detection signal is stored in float format.
%fs: The signal sample rate in Hertz.
%chunkSize: The chunk size used for the detection in seconds.
fid = fopen(file);
d = fread(fid, inf, 'float');
fclose(fid);
t = 0:(1 / fs):(length(d) * chunkSize - 1 / fs);
d = d(floor(t / chunkSize) + 1);
|
github
|
b-xiang/webrtc-master
|
readPCM.m
|
.m
|
webrtc-master/modules/audio_processing/transient/test/readPCM.m
| 821 |
utf_8
|
76b2955e65258ada1c1e549a4fc9bf79
|
%
% Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [x, t] = readPCM(file, fs)
%[x, t] = readPCM(file, fs)
%
%Reads a signal from a PCM file.
%
%x: The read signal after normalization.
%t: The respective time vector.
%
%file: The PCM file where the signal is stored in int16 format.
%fs: The signal sample rate in Hertz.
fid = fopen(file);
x = fread(fid, inf, 'int16');
fclose(fid);
x = x - mean(x);
x = x / max(abs(x));
t = 0:(1 / fs):((length(x) - 1) / fs);
|
github
|
b-xiang/webrtc-master
|
plotDetection.m
|
.m
|
webrtc-master/modules/audio_processing/transient/test/plotDetection.m
| 923 |
utf_8
|
e8113bdaf5dcfe4f50200a3ca29c3846
|
%
% Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [] = plotDetection(PCMfile, DATfile, fs, chunkSize)
%[] = plotDetection(PCMfile, DATfile, fs, chunkSize)
%
%Plots the signal alongside the detection values.
%
%PCMfile: The file of the input signal in PCM format.
%DATfile: The file containing the detection values in binary float format.
%fs: The sample rate of the signal in Hertz.
%chunkSize: The chunk size used to compute the detection values in seconds.
[x, tx] = readPCM(PCMfile, fs);
[d, td] = readDetection(DATfile, fs, chunkSize);
plot(tx, x, td, d);
|
github
|
b-xiang/webrtc-master
|
apmtest.m
|
.m
|
webrtc-master/modules/audio_processing/test/apmtest.m
| 9,874 |
utf_8
|
17ad6af59f6daa758d983dd419e46ff0
|
%
% Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function apmtest(task, testname, filepath, casenumber, legacy)
%APMTEST is a tool to process APM file sets and easily display the output.
% APMTEST(TASK, TESTNAME, CASENUMBER) performs one of several TASKs:
% 'test' Processes the files to produce test output.
% 'list' Prints a list of cases in the test set, preceded by their
% CASENUMBERs.
% 'show' Uses spclab to show the test case specified by the
% CASENUMBER parameter.
%
% using a set of test files determined by TESTNAME:
% 'all' All tests.
% 'apm' The standard APM test set (default).
% 'apmm' The mobile APM test set.
% 'aec' The AEC test set.
% 'aecm' The AECM test set.
% 'agc' The AGC test set.
% 'ns' The NS test set.
% 'vad' The VAD test set.
%
% FILEPATH specifies the path to the test data files.
%
% CASENUMBER can be used to select a single test case. Omit CASENUMBER,
% or set to zero, to use all test cases.
%
if nargin < 5 || isempty(legacy)
% Set to true to run old VQE recordings.
legacy = false;
end
if nargin < 4 || isempty(casenumber)
casenumber = 0;
end
if nargin < 3 || isempty(filepath)
filepath = 'data/';
end
if nargin < 2 || isempty(testname)
testname = 'all';
end
if nargin < 1 || isempty(task)
task = 'test';
end
if ~strcmp(task, 'test') && ~strcmp(task, 'list') && ~strcmp(task, 'show')
error(['TASK ' task ' is not recognized']);
end
if casenumber == 0 && strcmp(task, 'show')
error(['CASENUMBER must be specified for TASK ' task]);
end
inpath = [filepath 'input/'];
outpath = [filepath 'output/'];
refpath = [filepath 'reference/'];
if strcmp(testname, 'all')
tests = {'apm','apmm','aec','aecm','agc','ns','vad'};
else
tests = {testname};
end
if legacy
progname = './test';
else
progname = './process_test';
end
global farFile;
global nearFile;
global eventFile;
global delayFile;
global driftFile;
if legacy
farFile = 'vqeFar.pcm';
nearFile = 'vqeNear.pcm';
eventFile = 'vqeEvent.dat';
delayFile = 'vqeBuf.dat';
driftFile = 'vqeDrift.dat';
else
farFile = 'apm_far.pcm';
nearFile = 'apm_near.pcm';
eventFile = 'apm_event.dat';
delayFile = 'apm_delay.dat';
driftFile = 'apm_drift.dat';
end
simulateMode = false;
nErr = 0;
nCases = 0;
for i=1:length(tests)
simulateMode = false;
if strcmp(tests{i}, 'apm')
testdir = ['apm/'];
outfile = ['out'];
if legacy
opt = ['-ec 1 -agc 2 -nc 2 -vad 3'];
else
opt = ['--no_progress -hpf' ...
' -aec --drift_compensation -agc --fixed_digital' ...
' -ns --ns_moderate -vad'];
end
elseif strcmp(tests{i}, 'apm-swb')
simulateMode = true;
testdir = ['apm-swb/'];
outfile = ['out'];
if legacy
opt = ['-fs 32000 -ec 1 -agc 2 -nc 2'];
else
opt = ['--no_progress -fs 32000 -hpf' ...
' -aec --drift_compensation -agc --adaptive_digital' ...
' -ns --ns_moderate -vad'];
end
elseif strcmp(tests{i}, 'apmm')
testdir = ['apmm/'];
outfile = ['out'];
opt = ['-aec --drift_compensation -agc --fixed_digital -hpf -ns ' ...
'--ns_moderate'];
else
error(['TESTNAME ' tests{i} ' is not recognized']);
end
inpathtest = [inpath testdir];
outpathtest = [outpath testdir];
refpathtest = [refpath testdir];
if ~exist(inpathtest,'dir')
error(['Input directory ' inpathtest ' does not exist']);
end
if ~exist(refpathtest,'dir')
warning(['Reference directory ' refpathtest ' does not exist']);
end
[status, errMsg] = mkdir(outpathtest);
if (status == 0)
error(errMsg);
end
[nErr, nCases] = recurseDir(inpathtest, outpathtest, refpathtest, outfile, ...
progname, opt, simulateMode, nErr, nCases, task, casenumber, legacy);
if strcmp(task, 'test') || strcmp(task, 'show')
system(['rm ' farFile]);
system(['rm ' nearFile]);
if simulateMode == false
system(['rm ' eventFile]);
system(['rm ' delayFile]);
system(['rm ' driftFile]);
end
end
end
if ~strcmp(task, 'list')
if nErr == 0
fprintf(1, '\nAll files are bit-exact to reference\n', nErr);
else
fprintf(1, '\n%d files are NOT bit-exact to reference\n', nErr);
end
end
function [nErrOut, nCases] = recurseDir(inpath, outpath, refpath, ...
outfile, progname, opt, simulateMode, nErr, nCases, task, casenumber, ...
legacy)
global farFile;
global nearFile;
global eventFile;
global delayFile;
global driftFile;
dirs = dir(inpath);
nDirs = 0;
nErrOut = nErr;
for i=3:length(dirs) % skip . and ..
nDirs = nDirs + dirs(i).isdir;
end
if nDirs == 0
nCases = nCases + 1;
if casenumber == nCases || casenumber == 0
if strcmp(task, 'list')
fprintf([num2str(nCases) '. ' outfile '\n'])
else
vadoutfile = ['vad_' outfile '.dat'];
outfile = [outfile '.pcm'];
% Check for VAD test
vadTest = 0;
if ~isempty(findstr(opt, '-vad'))
vadTest = 1;
if legacy
opt = [opt ' ' outpath vadoutfile];
else
opt = [opt ' --vad_out_file ' outpath vadoutfile];
end
end
if exist([inpath 'vqeFar.pcm'])
system(['ln -s -f ' inpath 'vqeFar.pcm ' farFile]);
elseif exist([inpath 'apm_far.pcm'])
system(['ln -s -f ' inpath 'apm_far.pcm ' farFile]);
end
if exist([inpath 'vqeNear.pcm'])
system(['ln -s -f ' inpath 'vqeNear.pcm ' nearFile]);
elseif exist([inpath 'apm_near.pcm'])
system(['ln -s -f ' inpath 'apm_near.pcm ' nearFile]);
end
if exist([inpath 'vqeEvent.dat'])
system(['ln -s -f ' inpath 'vqeEvent.dat ' eventFile]);
elseif exist([inpath 'apm_event.dat'])
system(['ln -s -f ' inpath 'apm_event.dat ' eventFile]);
end
if exist([inpath 'vqeBuf.dat'])
system(['ln -s -f ' inpath 'vqeBuf.dat ' delayFile]);
elseif exist([inpath 'apm_delay.dat'])
system(['ln -s -f ' inpath 'apm_delay.dat ' delayFile]);
end
if exist([inpath 'vqeSkew.dat'])
system(['ln -s -f ' inpath 'vqeSkew.dat ' driftFile]);
elseif exist([inpath 'vqeDrift.dat'])
system(['ln -s -f ' inpath 'vqeDrift.dat ' driftFile]);
elseif exist([inpath 'apm_drift.dat'])
system(['ln -s -f ' inpath 'apm_drift.dat ' driftFile]);
end
if simulateMode == false
command = [progname ' -o ' outpath outfile ' ' opt];
else
if legacy
inputCmd = [' -in ' nearFile];
else
inputCmd = [' -i ' nearFile];
end
if exist([farFile])
if legacy
inputCmd = [' -if ' farFile inputCmd];
else
inputCmd = [' -ir ' farFile inputCmd];
end
end
command = [progname inputCmd ' -o ' outpath outfile ' ' opt];
end
% This prevents MATLAB from using its own C libraries.
shellcmd = ['bash -c "unset LD_LIBRARY_PATH;'];
fprintf([command '\n']);
[status, result] = system([shellcmd command '"']);
fprintf(result);
fprintf(['Reference file: ' refpath outfile '\n']);
if vadTest == 1
equal_to_ref = are_files_equal([outpath vadoutfile], ...
[refpath vadoutfile], ...
'int8');
if ~equal_to_ref
nErr = nErr + 1;
end
end
[equal_to_ref, diffvector] = are_files_equal([outpath outfile], ...
[refpath outfile], ...
'int16');
if ~equal_to_ref
nErr = nErr + 1;
end
if strcmp(task, 'show')
% Assume the last init gives the sample rate of interest.
str_idx = strfind(result, 'Sample rate:');
fs = str2num(result(str_idx(end) + 13:str_idx(end) + 17));
fprintf('Using %d Hz\n', fs);
if exist([farFile])
spclab(fs, farFile, nearFile, [refpath outfile], ...
[outpath outfile], diffvector);
%spclab(fs, diffvector);
else
spclab(fs, nearFile, [refpath outfile], [outpath outfile], ...
diffvector);
%spclab(fs, diffvector);
end
end
end
end
else
for i=3:length(dirs)
if dirs(i).isdir
[nErr, nCases] = recurseDir([inpath dirs(i).name '/'], outpath, ...
refpath,[outfile '_' dirs(i).name], progname, opt, ...
simulateMode, nErr, nCases, task, casenumber, legacy);
end
end
end
nErrOut = nErr;
function [are_equal, diffvector] = ...
are_files_equal(newfile, reffile, precision, diffvector)
are_equal = false;
diffvector = 0;
if ~exist(newfile,'file')
warning(['Output file ' newfile ' does not exist']);
return
end
if ~exist(reffile,'file')
warning(['Reference file ' reffile ' does not exist']);
return
end
fid = fopen(newfile,'rb');
new = fread(fid,inf,precision);
fclose(fid);
fid = fopen(reffile,'rb');
ref = fread(fid,inf,precision);
fclose(fid);
if length(new) ~= length(ref)
warning('Reference is not the same length as output');
minlength = min(length(new), length(ref));
new = new(1:minlength);
ref = ref(1:minlength);
end
diffvector = new - ref;
if isequal(new, ref)
fprintf([newfile ' is bit-exact to reference\n']);
are_equal = true;
else
if isempty(new)
warning([newfile ' is empty']);
return
end
snr = snrseg(new,ref,80);
fprintf('\n');
are_equal = false;
end
|
github
|
b-xiang/webrtc-master
|
parse_delay_file.m
|
.m
|
webrtc-master/modules/audio_coding/neteq/test/delay_tool/parse_delay_file.m
| 6,405 |
utf_8
|
4cc70d6f90e1ca5901104f77a7e7c0b3
|
%
% Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function outStruct = parse_delay_file(file)
fid = fopen(file, 'rb');
if fid == -1
error('Cannot open file %s', file);
end
textline = fgetl(fid);
if ~strncmp(textline, '#!NetEQ_Delay_Logging', 21)
error('Wrong file format');
end
ver = sscanf(textline, '#!NetEQ_Delay_Logging%d.%d');
if ~all(ver == [2; 0])
error('Wrong version of delay logging function')
end
start_pos = ftell(fid);
fseek(fid, -12, 'eof');
textline = fgetl(fid);
if ~strncmp(textline, 'End of file', 21)
error('File ending is not correct. Seems like the simulation ended abnormally.');
end
fseek(fid,-12-4, 'eof');
Npackets = fread(fid, 1, 'int32');
fseek(fid, start_pos, 'bof');
rtpts = zeros(Npackets, 1);
seqno = zeros(Npackets, 1);
pt = zeros(Npackets, 1);
plen = zeros(Npackets, 1);
recin_t = nan*ones(Npackets, 1);
decode_t = nan*ones(Npackets, 1);
playout_delay = zeros(Npackets, 1);
optbuf = zeros(Npackets, 1);
fs_ix = 1;
clock = 0;
ts_ix = 1;
ended = 0;
late_packets = 0;
fs_now = 8000;
last_decode_k = 0;
tot_expand = 0;
tot_accelerate = 0;
tot_preemptive = 0;
while not(ended)
signal = fread(fid, 1, '*int32');
switch signal
case 3 % NETEQ_DELAY_LOGGING_SIGNAL_CLOCK
clock = fread(fid, 1, '*float32');
% keep on reading batches of M until the signal is no longer "3"
% read int32 + float32 in one go
% this is to save execution time
temp = [3; 0];
M = 120;
while all(temp(1,:) == 3)
fp = ftell(fid);
temp = fread(fid, [2 M], '*int32');
end
% back up to last clock event
fseek(fid, fp - ftell(fid) + ...
(find(temp(1,:) ~= 3, 1 ) - 2) * 2 * 4 + 4, 'cof');
% read the last clock value
clock = fread(fid, 1, '*float32');
case 1 % NETEQ_DELAY_LOGGING_SIGNAL_RECIN
temp_ts = fread(fid, 1, 'uint32');
if late_packets > 0
temp_ix = ts_ix - 1;
while (temp_ix >= 1) && (rtpts(temp_ix) ~= temp_ts)
% TODO(hlundin): use matlab vector search instead?
temp_ix = temp_ix - 1;
end
if temp_ix >= 1
% the ts was found in the vector
late_packets = late_packets - 1;
else
temp_ix = ts_ix;
ts_ix = ts_ix + 1;
end
else
temp_ix = ts_ix;
ts_ix = ts_ix + 1;
end
rtpts(temp_ix) = temp_ts;
seqno(temp_ix) = fread(fid, 1, 'uint16');
pt(temp_ix) = fread(fid, 1, 'int32');
plen(temp_ix) = fread(fid, 1, 'int16');
recin_t(temp_ix) = clock;
case 2 % NETEQ_DELAY_LOGGING_SIGNAL_FLUSH
% do nothing
case 4 % NETEQ_DELAY_LOGGING_SIGNAL_EOF
ended = 1;
case 5 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE
last_decode_ts = fread(fid, 1, 'uint32');
temp_delay = fread(fid, 1, 'uint16');
k = find(rtpts(1:(ts_ix - 1))==last_decode_ts,1,'last');
if ~isempty(k)
decode_t(k) = clock;
playout_delay(k) = temp_delay + ...
5 * fs_now / 8000; % add overlap length
last_decode_k = k;
end
case 6 % NETEQ_DELAY_LOGGING_SIGNAL_CHANGE_FS
fsvec(fs_ix) = fread(fid, 1, 'uint16');
fschange_ts(fs_ix) = last_decode_ts;
fs_now = fsvec(fs_ix);
fs_ix = fs_ix + 1;
case 7 % NETEQ_DELAY_LOGGING_SIGNAL_MERGE_INFO
playout_delay(last_decode_k) = playout_delay(last_decode_k) ...
+ fread(fid, 1, 'int32');
case 8 % NETEQ_DELAY_LOGGING_SIGNAL_EXPAND_INFO
temp = fread(fid, 1, 'int32');
if last_decode_k ~= 0
tot_expand = tot_expand + temp / (fs_now / 1000);
end
case 9 % NETEQ_DELAY_LOGGING_SIGNAL_ACCELERATE_INFO
temp = fread(fid, 1, 'int32');
if last_decode_k ~= 0
tot_accelerate = tot_accelerate + temp / (fs_now / 1000);
end
case 10 % NETEQ_DELAY_LOGGING_SIGNAL_PREEMPTIVE_INFO
temp = fread(fid, 1, 'int32');
if last_decode_k ~= 0
tot_preemptive = tot_preemptive + temp / (fs_now / 1000);
end
case 11 % NETEQ_DELAY_LOGGING_SIGNAL_OPTBUF
optbuf(last_decode_k) = fread(fid, 1, 'int32');
case 12 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE_ONE_DESC
last_decode_ts = fread(fid, 1, 'uint32');
k = ts_ix - 1;
while (k >= 1) && (rtpts(k) ~= last_decode_ts)
% TODO(hlundin): use matlab vector search instead?
k = k - 1;
end
if k < 1
% packet not received yet
k = ts_ix;
rtpts(ts_ix) = last_decode_ts;
late_packets = late_packets + 1;
end
decode_t(k) = clock;
playout_delay(k) = fread(fid, 1, 'uint16') + ...
5 * fs_now / 8000; % add overlap length
last_decode_k = k;
end
end
fclose(fid);
outStruct = struct(...
'ts', rtpts, ...
'sn', seqno, ...
'pt', pt,...
'plen', plen,...
'arrival', recin_t,...
'decode', decode_t,...
'fs', fsvec(:),...
'fschange_ts', fschange_ts(:),...
'playout_delay', playout_delay,...
'tot_expand', tot_expand,...
'tot_accelerate', tot_accelerate,...
'tot_preemptive', tot_preemptive,...
'optbuf', optbuf);
|
github
|
b-xiang/webrtc-master
|
plot_neteq_delay.m
|
.m
|
webrtc-master/modules/audio_coding/neteq/test/delay_tool/plot_neteq_delay.m
| 5,967 |
utf_8
|
cce342fed6406ef0f12d567fe3ab6eef
|
%
% Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [delay_struct, delayvalues] = plot_neteq_delay(delayfile, varargin)
% InfoStruct = plot_neteq_delay(delayfile)
% InfoStruct = plot_neteq_delay(delayfile, 'skipdelay', skip_seconds)
%
% Henrik Lundin, 2006-11-17
% Henrik Lundin, 2011-05-17
%
try
s = parse_delay_file(delayfile);
catch
error(lasterr);
end
delayskip=0;
noplot=0;
arg_ptr=1;
delaypoints=[];
s.sn=unwrap_seqno(s.sn);
while arg_ptr+1 <= nargin
switch lower(varargin{arg_ptr})
case {'skipdelay', 'delayskip'}
% skip a number of seconds in the beginning when calculating delays
delayskip = varargin{arg_ptr+1};
arg_ptr = arg_ptr + 2;
case 'noplot'
noplot=1;
arg_ptr = arg_ptr + 1;
case {'get_delay', 'getdelay'}
% return a vector of delay values for the points in the given vector
delaypoints = varargin{arg_ptr+1};
arg_ptr = arg_ptr + 2;
otherwise
warning('Unknown switch %s\n', varargin{arg_ptr});
arg_ptr = arg_ptr + 1;
end
end
% find lost frames that were covered by one-descriptor decoding
one_desc_ix=find(isnan(s.arrival));
for k=1:length(one_desc_ix)
ix=find(s.ts==max(s.ts(s.ts(one_desc_ix(k))>s.ts)));
s.sn(one_desc_ix(k))=s.sn(ix)+1;
s.pt(one_desc_ix(k))=s.pt(ix);
s.arrival(one_desc_ix(k))=s.arrival(ix)+s.decode(one_desc_ix(k))-s.decode(ix);
end
% remove duplicate received frames that were never decoded (RED codec)
if length(unique(s.ts(isfinite(s.ts)))) < length(s.ts(isfinite(s.ts)))
ix=find(isfinite(s.decode));
s.sn=s.sn(ix);
s.ts=s.ts(ix);
s.arrival=s.arrival(ix);
s.playout_delay=s.playout_delay(ix);
s.pt=s.pt(ix);
s.optbuf=s.optbuf(ix);
plen=plen(ix);
s.decode=s.decode(ix);
end
% find non-unique sequence numbers
[~,un_ix]=unique(s.sn);
nonun_ix=setdiff(1:length(s.sn),un_ix);
if ~isempty(nonun_ix)
warning('RTP sequence numbers are in error');
end
% sort vectors
[s.sn,sort_ix]=sort(s.sn);
s.ts=s.ts(sort_ix);
s.arrival=s.arrival(sort_ix);
s.decode=s.decode(sort_ix);
s.playout_delay=s.playout_delay(sort_ix);
s.pt=s.pt(sort_ix);
send_t=s.ts-s.ts(1);
if length(s.fs)<1
warning('No info about sample rate found in file. Using default 8000.');
s.fs(1)=8000;
s.fschange_ts(1)=min(s.ts);
elseif s.fschange_ts(1)>min(s.ts)
s.fschange_ts(1)=min(s.ts);
end
end_ix=length(send_t);
for k=length(s.fs):-1:1
start_ix=find(s.ts==s.fschange_ts(k));
send_t(start_ix:end_ix)=send_t(start_ix:end_ix)/s.fs(k)*1000;
s.playout_delay(start_ix:end_ix)=s.playout_delay(start_ix:end_ix)/s.fs(k)*1000;
s.optbuf(start_ix:end_ix)=s.optbuf(start_ix:end_ix)/s.fs(k)*1000;
end_ix=start_ix-1;
end
tot_time=max(send_t)-min(send_t);
seq_ix=s.sn-min(s.sn)+1;
send_t=send_t+max(min(s.arrival-send_t),0);
plot_send_t=nan*ones(max(seq_ix),1);
plot_send_t(seq_ix)=send_t;
plot_nw_delay=nan*ones(max(seq_ix),1);
plot_nw_delay(seq_ix)=s.arrival-send_t;
cng_ix=find(s.pt~=13); % find those packets that are not CNG/SID
if noplot==0
h=plot(plot_send_t/1000,plot_nw_delay);
set(h,'color',0.75*[1 1 1]);
hold on
if any(s.optbuf~=0)
peak_ix=find(s.optbuf(cng_ix)<0); % peak mode is labeled with negative values
no_peak_ix=find(s.optbuf(cng_ix)>0); %setdiff(1:length(cng_ix),peak_ix);
h1=plot(send_t(cng_ix(peak_ix))/1000,...
s.arrival(cng_ix(peak_ix))+abs(s.optbuf(cng_ix(peak_ix)))-send_t(cng_ix(peak_ix)),...
'r.');
h2=plot(send_t(cng_ix(no_peak_ix))/1000,...
s.arrival(cng_ix(no_peak_ix))+abs(s.optbuf(cng_ix(no_peak_ix)))-send_t(cng_ix(no_peak_ix)),...
'g.');
set([h1, h2],'markersize',1)
end
%h=plot(send_t(seq_ix)/1000,s.decode+s.playout_delay-send_t(seq_ix));
h=plot(send_t(cng_ix)/1000,s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix));
set(h,'linew',1.5);
hold off
ax1=axis;
axis tight
ax2=axis;
axis([ax2(1:3) ax1(4)])
end
% calculate delays and other parameters
delayskip_ix = find(send_t-send_t(1)>=delayskip*1000, 1 );
use_ix = intersect(cng_ix,... % use those that are not CNG/SID frames...
intersect(find(isfinite(s.decode)),... % ... that did arrive ...
(delayskip_ix:length(s.decode))')); % ... and are sent after delayskip seconds
mean_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-send_t(use_ix));
neteq_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-s.arrival(use_ix));
Npack=max(s.sn(delayskip_ix:end))-min(s.sn(delayskip_ix:end))+1;
nw_lossrate=(Npack-length(s.sn(delayskip_ix:end)))/Npack;
neteq_lossrate=(length(s.sn(delayskip_ix:end))-length(use_ix))/Npack;
delay_struct=struct('mean_delay',mean_delay,'neteq_delay',neteq_delay,...
'nw_lossrate',nw_lossrate,'neteq_lossrate',neteq_lossrate,...
'tot_expand',round(s.tot_expand),'tot_accelerate',round(s.tot_accelerate),...
'tot_preemptive',round(s.tot_preemptive),'tot_time',tot_time,...
'filename',delayfile,'units','ms','fs',unique(s.fs));
if not(isempty(delaypoints))
delayvalues=interp1(send_t(cng_ix),...
s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix),...
delaypoints,'nearest',NaN);
else
delayvalues=[];
end
% SUBFUNCTIONS %
function y=unwrap_seqno(x)
jumps=find(abs((diff(x)-1))>65000);
while ~isempty(jumps)
n=jumps(1);
if x(n+1)-x(n) < 0
% negative jump
x(n+1:end)=x(n+1:end)+65536;
else
% positive jump
x(n+1:end)=x(n+1:end)-65536;
end
jumps=find(abs((diff(x(n+1:end))-1))>65000);
end
y=x;
return;
|
github
|
b-xiang/webrtc-master
|
rtpAnalyze.m
|
.m
|
webrtc-master/tools_webrtc/matlab/rtpAnalyze.m
| 7,892 |
utf_8
|
46e63db0fa96270c14a0c205bbab42e4
|
function rtpAnalyze( input_file )
%RTP_ANALYZE Analyze RTP stream(s) from a txt file
% The function takes the output from the command line tool rtp_analyze
% and analyzes the stream(s) therein. First, process your rtpdump file
% through rtp_analyze (from command line):
% $ out/Debug/rtp_analyze my_file.rtp my_file.txt
% Then load it with this function (in Matlab):
% >> rtpAnalyze('my_file.txt')
% Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
[SeqNo,TimeStamp,ArrTime,Size,PT,M,SSRC] = importfile(input_file);
%% Filter out RTCP packets.
% These appear as RTP packets having payload types 72 through 76.
ix = not(ismember(PT, 72:76));
fprintf('Removing %i RTCP packets\n', length(SeqNo) - sum(ix));
SeqNo = SeqNo(ix);
TimeStamp = TimeStamp(ix);
ArrTime = ArrTime(ix);
Size = Size(ix);
PT = PT(ix);
M = M(ix);
SSRC = SSRC(ix);
%% Find streams.
[uSSRC, ~, uix] = unique(SSRC);
% If there are multiple streams, select one and purge the other
% streams from the data vectors. If there is only one stream, the
% vectors are good to use as they are.
if length(uSSRC) > 1
for i=1:length(uSSRC)
uPT = unique(PT(uix == i));
fprintf('%i: %s (%d packets, pt: %i', i, uSSRC{i}, ...
length(find(uix==i)), uPT(1));
if length(uPT) > 1
fprintf(', %i', uPT(2:end));
end
fprintf(')\n');
end
sel = input('Select stream number: ');
if sel < 1 || sel > length(uSSRC)
error('Out of range');
end
ix = find(uix == sel);
% This is where the data vectors are trimmed.
SeqNo = SeqNo(ix);
TimeStamp = TimeStamp(ix);
ArrTime = ArrTime(ix);
Size = Size(ix);
PT = PT(ix);
M = M(ix);
SSRC = SSRC(ix);
end
%% Unwrap SeqNo and TimeStamp.
SeqNoUW = maxUnwrap(SeqNo, 65535);
TimeStampUW = maxUnwrap(TimeStamp, 4294967295);
%% Generate some stats for the stream.
fprintf('Statistics:\n');
fprintf('SSRC: %s\n', SSRC{1});
uPT = unique(PT);
if length(uPT) > 1
warning('This tool cannot yet handle changes in codec sample rate');
end
fprintf('Payload type(s): %i', uPT(1));
if length(uPT) > 1
fprintf(', %i', uPT(2:end));
end
fprintf('\n');
fprintf('Packets: %i\n', length(SeqNo));
SortSeqNo = sort(SeqNoUW);
fprintf('Missing sequence numbers: %i\n', ...
length(find(diff(SortSeqNo) > 1)));
fprintf('Duplicated packets: %i\n', length(find(diff(SortSeqNo) == 0)));
reorderIx = findReorderedPackets(SeqNoUW);
fprintf('Reordered packets: %i\n', length(reorderIx));
tsdiff = diff(TimeStampUW);
tsdiff = tsdiff(diff(SeqNoUW) == 1);
[utsdiff, ~, ixtsdiff] = unique(tsdiff);
fprintf('Common packet sizes:\n');
for i = 1:length(utsdiff)
fprintf(' %i samples (%i%%)\n', ...
utsdiff(i), ...
round(100 * length(find(ixtsdiff == i))/length(ixtsdiff)));
end
%% Trying to figure out sample rate.
fs_est = (TimeStampUW(end) - TimeStampUW(1)) / (ArrTime(end) - ArrTime(1));
fs_vec = [8, 16, 32, 48];
fs = 0;
for f = fs_vec
if abs((fs_est-f)/f) < 0.05 % 5% margin
fs = f;
break;
end
end
if fs == 0
fprintf('Cannot determine sample rate. I get it to %.2f kHz\n', ...
fs_est);
fs = input('Please, input a sample rate (in kHz): ');
else
fprintf('Sample rate estimated to %i kHz\n', fs);
end
SendTimeMs = (TimeStampUW - TimeStampUW(1)) / fs;
fprintf('Stream duration at sender: %.1f seconds\n', ...
(SendTimeMs(end) - SendTimeMs(1)) / 1000);
fprintf('Stream duration at receiver: %.1f seconds\n', ...
(ArrTime(end) - ArrTime(1)) / 1000);
fprintf('Clock drift: %.2f%%\n', ...
100 * ((ArrTime(end) - ArrTime(1)) / ...
(SendTimeMs(end) - SendTimeMs(1)) - 1));
fprintf('Sent average bitrate: %i kbps\n', ...
round(sum(Size) * 8 / (SendTimeMs(end)-SendTimeMs(1))));
fprintf('Received average bitrate: %i kbps\n', ...
round(sum(Size) * 8 / (ArrTime(end)-ArrTime(1))));
%% Plots.
delay = ArrTime - SendTimeMs;
delay = delay - min(delay);
delayOrdered = delay;
delayOrdered(reorderIx) = nan; % Set reordered packets to NaN.
delayReordered = delay(reorderIx); % Pick the reordered packets.
sendTimeMsReordered = SendTimeMs(reorderIx);
% Sort time arrays in packet send order.
[~, sortix] = sort(SeqNoUW);
SendTimeMs = SendTimeMs(sortix);
Size = Size(sortix);
delayOrdered = delayOrdered(sortix);
figure
plot(SendTimeMs / 1000, delayOrdered, ...
sendTimeMsReordered / 1000, delayReordered, 'r.');
xlabel('Send time [s]');
ylabel('Relative transport delay [ms]');
title(sprintf('SSRC: %s', SSRC{1}));
SendBitrateKbps = 8 * Size(1:end-1) ./ diff(SendTimeMs);
figure
plot(SendTimeMs(1:end-1)/1000, SendBitrateKbps);
xlabel('Send time [s]');
ylabel('Send bitrate [kbps]');
end
%% Subfunctions.
% findReorderedPackets returns the index to all packets that are considered
% old compared with the largest seen sequence number. The input seqNo must
% be unwrapped for this to work.
function reorderIx = findReorderedPackets(seqNo)
largestSeqNo = seqNo(1);
reorderIx = [];
for i = 2:length(seqNo)
if seqNo(i) < largestSeqNo
reorderIx = [reorderIx; i]; %#ok<AGROW>
else
largestSeqNo = seqNo(i);
end
end
end
%% Auto-generated subfunction.
function [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = ...
importfile(filename, startRow, endRow)
%IMPORTFILE Import numeric data from a text file as column vectors.
% [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME) Reads
% data from text file FILENAME for the default selection.
%
% [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME,
% STARTROW, ENDROW) Reads data from rows STARTROW through ENDROW of text
% file FILENAME.
%
% Example:
% [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] =
% importfile('rtpdump_recv.txt',2, 123);
%
% See also TEXTSCAN.
% Auto-generated by MATLAB on 2015/05/28 09:55:50
%% Initialize variables.
if nargin<=2
startRow = 2;
endRow = inf;
end
%% Format string for each line of text:
% column1: double (%f)
% column2: double (%f)
% column3: double (%f)
% column4: double (%f)
% column5: double (%f)
% column6: double (%f)
% column7: text (%s)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%5f%11f%11f%6f%6f%3f%s%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, ...
'Delimiter', '', 'WhiteSpace', '', 'HeaderLines', startRow(1)-1, ...
'ReturnOnError', false);
for block=2:length(startRow)
frewind(fileID);
dataArrayBlock = textscan(fileID, formatSpec, ...
endRow(block)-startRow(block)+1, 'Delimiter', '', 'WhiteSpace', ...
'', 'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
for col=1:length(dataArray)
dataArray{col} = [dataArray{col};dataArrayBlock{col}];
end
end
%% Close the text file.
fclose(fileID);
%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.
%% Allocate imported array to column variable names
SeqNo = dataArray{:, 1};
TimeStamp = dataArray{:, 2};
SendTime = dataArray{:, 3};
Size = dataArray{:, 4};
PT = dataArray{:, 5};
M = dataArray{:, 6};
SSRC = dataArray{:, 7};
end
|
github
|
markcannon/markcannon.github.io-master
|
sim_qpmin_d.m
|
.m
|
markcannon.github.io-master/assets/downloads/teaching/C21_Model_Predictive_Control/mcode/sim_qpmin_d.m
| 4,036 |
utf_8
|
ac2c23994b018bcb45e4309d2060e82b
|
function [t,z,u,y,J,Jrun,info] = ...
sim_qpmin_d(x0,Bd,d,dbnd,N,s,p,w,c,opt_flag,options)
%sim_qpmin Simulate closed-loop response for QP-based control law.
% [t,z,u,y,J,info] = sim_qpmin(x0,s,p,w,c,options)
% Input arguments:
% x0 -- initial plant state
% s -- plant state space model
% p -- structure containing prediction model parameters:
% p.nx, p.nu, p.nc, p.Phi, p.K, p.umax (see predmodel)
% w -- structure containing cost matrices
% w.Qcost, w.Rcost, w.P, w.W (see predmodel)
% w.Pf (finite horizon cost, see fh_cost)
% c -- structure containing linear constraint matrices
% c.A,c.Bx,c.b (see linconstr)
% opt_flag -- 0 => finite horizon cost (u=0 assumed in mode2 predictions)
% 1 => infinite horizon cost
% options -- set options.Display = 'off' to supress messages
% Returns:
% t,z,u,y -- sample times and responses of state, inputs and outputs
% J -- infinite horizon closed-loop cost
% info -- optimization status
if nargin < 11
options = optimset('quadprog');
%options.Display = 'off';
options.LargeScale = 'off';
end
if (nargin < 7 || isempty(opt_flag)), opt_flag = 1; end
% objective for QP objective
if opt_flag
H = [];
for i = 1:p.nc
H = blkdiag(H,w.W);
end
H = 0.5*(H+H');
G = zeros(p.nu*p.nc,p.nx);
F = w.P;
else
H = w.Pf(p.nx+1:end,p.nx+1:end);
G = w.Pf(p.nx+1:end,1:p.nx);
F = w.Pf(1:p.nx,1:p.nx);
end
if size(dbnd,2) > 0
AA = []; BBx = []; bb = [];
for i = 1:size(dbnd,2)
bb = [bb;c.b+c.Bd*dbnd(:,i)]; %#ok<*AGROW>
AA = [AA;c.A]; BBx = [BBx;c.Bx];
end
else
AA = c.A; BBx = c.Bx; bb = c.b;
end
x_k = x0; Jrun = 0; flag = 1; k = 1; z = []; u = zeros(p.nu,0); y = []; J = [];
while flag && k <= N+1
[c_k,obj,eflag1,~,lam] = quadprog(H,G*x_k,...
AA,BBx*x_k+bb,...
[],[],[],[],[],options);
if max(lam.ineqlin) == 0 % unconstrained optimal is feasible
[N,x_lq,u_lq,y_lq,J_lq] = sim_lq(x_k,Bd,d,Jrun,...
s,p,w,F,-p.umax,p.umax,N-k+1);
z = [z,[x_lq;zeros(p.nc,N)]]; u = [u,u_lq]; y = [y,y_lq];
J = [J,J_lq];
Jrun = Jrun + x_k'*w.P*x_k;
info(:,k) = eflag1;
flag = 0;
elseif eflag1 == -1
Jrun = -1;
flag = 0;
else
% u_k = p.K*[x_k;c_k];
u_k = satu(p.K*[x_k;c_k],-p.umax,p.umax);
Jrun = Jrun + x_k'*w.Qcost*x_k + u_k'*w.Rcost*u_k;
Jpred = 2*obj + x_k'*F*x_k;
z(:,k) = [x_k;c_k];
u(:,k) = u_k;
y(:,k) = s.C*x_k;
J(:,k) = [Jpred;Jrun];
info(:,k) = eflag1;
x_k = s.A*x_k + s.B*u_k + Bd*d;
k = k+1;
end
end
t = 0:(size(z,2)-1);
%------------------------------------------------------------------------------
function [N,x,u,y,J] = sim_lq(x0,Bd,d,Jrun,s,p,w,F,umin,umax,NN)
% Closed-loop response under LQ feedback
x_k = x0; r0 = 1e-3*norm(x_k,2); k = 1;
while (norm(x_k,2) >= r0 || k <= NN) && k < 100
u_k = satu(p.K(:,1:p.nx)*x_k,umin,umax);
% u_k = p.K(:,1:p.nx)*x_k;
Jrun = Jrun + x_k'*w.Qcost*x_k + u_k'*w.Rcost*u_k;
Jpred = x_k'*F*x_k;
x(:,k) = x_k;
u(:,k) = u_k;
y(:,k) = s.C*x_k;
J(:,k) = [Jpred;Jrun];
x_k = s.A*x_k + s.B*u_k + Bd*d;
k = k+1;
end
N = k-1;
%------------------------------------------------------------------------------
function [x,u,y] = sim_pred(x0,c0,s,p,N,opt_flag) %#ok<DEFNU>
if nargin < 6 || isempty(opt_flag), opt_flag = 1; end
if nargin < 5 || isempty(N) || N < p.nc, N = p.nc; end
% Predicted response
x_k = x0; z_k = [x0;c0]; k = 1;
while k <= N
if (k <= p.nc || opt_flag)
u_k = p.K*z_k;
else % FH mode 2
u_k = 0;
end
x(:,k) = x_k;
u(:,k) = u_k;
y(:,k) = s.C*x_k;
if (k <= p.nc || opt_flag)
z_k = p.Phi*z_k;
x_k = z_k(1:p.nx);
else % FH mode 2
x_k = s.A*x_k;
end
k = k+1;
end
x(:,k) = x_k;
y(:,k) = s.C*x_k;
%------------------------------------------------------------------------------
function u = satu(u,umin,umax)
if u > umax
u = umax;
elseif u < umin
u = umin;
end
|
github
|
CankayaUniversity/ceng-407-408-2017-2018-project-blood-vessel-segmentation-master
|
segmentation.m
|
.m
|
ceng-407-408-2017-2018-project-blood-vessel-segmentation-master/Project/segmentation.m
| 695 |
utf_8
|
8468fbee34ea6573785311ec6c4a67c8
|
% Segmentation function.
function [ves] = segmentation(path)
% Read image.
im=imread(path);
% Image enhancement & gray scale of a green channel image.
image = imageEnhancement(im);
% Load network.
load net;
[m,n] = size(image);
ves=uint8(zeros(size(image)));
% Classification.
for i = 1:1:m-(9-1)
for j = 1:1:n-(9-1)
patch=image(i:i+(9-1),j:j+(9-1));
if isBlackSpot(patch)==0
x=net.classify(patch);
if x=='Positive' % if positive, binarize for the center pixel.
ves((i+(i+(9-1)))/2,(j+(j+(9-1)))/2)=255;
end
end
end
end
% Final image 'ves' constructed.
end
|
github
|
UGM-Geofisika/Dispersion_Inversion-master
|
main.m
|
.m
|
Dispersion_Inversion-master/main.m
| 35,750 |
utf_8
|
d9dada994aca8aadc9c712bc8898076f
|
function varargout = main(varargin)
% MAIN MATLAB code for main.fig
% MAIN, by itself, creates a new MAIN or raises the existing
% singleton*.
%
% H = MAIN returns the handle to a new MAIN or the handle to
% the existing singleton*.
%
% MAIN('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MAIN.M with the given input arguments.
%
% MAIN('Property','Value',...) creates a new MAIN or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before main_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to main_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
%
% Author: Pablo Pizarro @ppizarror.com, 2017.
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
%
% Last Modified by GUIDE v2.5 09-Feb-2017 16:09:04
%
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @main_OpeningFcn, ...
'gui_OutputFcn', @main_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 main is made visible.
function main_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 main (see VARARGIN)
% Choose default command line output for main
handles.output = hObject;
% Add bin, and gui to path from folder (recursive)
PATH_DEPTH = 3;
for i=1:PATH_DEPTH
try
path_str = '';
if i~=1
for j=1:i-1
path_str = strcat(path_str, '../');
end
end
path_bin = cd(cd(strcat(path_str, 'bin')));
path_gui = cd(cd(strcat(path_str, 'gui')));
addpath(path_bin);
addpath(path_gui);
break
catch Exception
% Folders could not be found
if i==PATH_DEPTH
fprintf(getReport(Exception));
error('Error while setting software path.');
end
end
end
% Center window
movegui(gcf, 'center');
% Import configurations
config;
% Load language strings
lang = load_lang(lang_id);
% Disable Excel warning
warning('off', 'MATLAB:xlswrite:AddSheet');
% Set gui-app config
setappdata(handles.root, 'lang', lang);
setappdata(handles.root, 'gui_sound', gui_sound_enabled);
setappdata(handles.root, 'delete_entry_if_invalid', delete_entry_if_invalid);
% Set inversion config
setappdata(handles.root, 'cgf_sigma', inv_sigma);
setappdata(handles.root, 'cgf_mu', inv_mu);
setappdata(handles.root, 'cgf_maxiter', inv_maxiter);
setappdata(handles.root, 'cgf_tolvs', inv_tol_vs);
% Set plot configuration - style
setappdata(handles.root, 'plt_disp_labl_fontsize', plt_dispersion_label_fontsize);
setappdata(handles.root, 'plt_dispersion_style', plt_dispersion_style);
setappdata(handles.root, 'sol_plot_disp_fontsize', solution_plt_dispersion_fontsize);
setappdata(handles.root, 'sol_plot_disp_style_exp', solution_plt_dispersion_experimental_style);
setappdata(handles.root, 'sol_plot_disp_style_sol', solution_plt_dispersion_solution_style);
setappdata(handles.root, 'plt_dispersion_showlegend', plt_dispersion_show_legend);
setappdata(handles.root, 'plt_dispersion_solution_showlegend', solution_plt_dispersion_show_legend);
setappdata(handles.root, 'sol_plot_shear_showlegend', solution_plt_shear_show_legend);
setappdata(handles.root, 'sol_plot_shear_fontsize', solution_plt_shear_fontsize);
setappdata(handles.root, 'dispersion_iteration_style', dispersion_iteration_style);
setappdata(handles.root, 'dispersion_iteration_fontsize', dispersion_iteration_fontsize);
setappdata(handles.root, 'dispersion_iteration_color', dispersion_iteration_color);
setappdata(handles.root, 'dispersion_iteration_random_color', dispersion_iteration_random_color);
setappdata(handles.root, 'dispersion_iteration_show_legend', dispersion_iteration_show_legend);
setappdata(handles.root, 'solution_plt_shear_curve_style', solution_plt_shear_curve_style);
setappdata(handles.root, 'dispersion_iteration_linewidth', dispersion_iteration_linewidth);
setappdata(handles.root, 'plt_dispersion_linewidth', plt_dispersion_linewidth);
setappdata(handles.root, 'solution_plt_dispersion_experimental_linewidth', ...
solution_plt_dispersion_experimental_linewidth);
setappdata(handles.root, 'solution_plt_dispersion_linewidth', ...
solution_plt_dispersion_linewidth);
setappdata(handles.root, 'solution_plot_shear_linewidth', ...
solution_plot_shear_linewidth);
setappdata(handles.root, 'solution_shear_comparision_fontsize', ...
solution_shear_comparision_fontsize);
setappdata(handles.root, 'solution_shear_comparision_shear_curve_linewidth', ...
solution_shear_comparision_shear_curve_linewidth);
setappdata(handles.root, 'solution_shear_comparision_iguess_curve_linewidth', ...
solution_shear_comparision_iguess_curve_linewidth);
setappdata(handles.root, 'solution_shear_comparision_shear_curve_style', ...
solution_shear_comparision_shear_curve_style);
setappdata(handles.root, 'solution_shear_comparision_iguess_curve_style', ...
solution_shear_comparision_iguess_curve_style);
setappdata(handles.root, 'solution_plt_shear_comparision_legend', ...
solution_plt_shear_comparision_legend);
% Set solution configuration
setappdata(handles.root, 'show_dispersion_comparision', show_dispersion_comparision);
setappdata(handles.root, 'show_shear_velocity_plot', show_shear_velocity_plot);
setappdata(handles.root, 'show_dispersion_iterations', show_dispersion_iterations);
setappdata(handles.root, 'show_shear_velocity_comparision', show_shear_velocity_comparision);
% Set GUI Strings from lang
set_gui_lang(handles, lang);
% Set new file
new_file(handles, lang, false);
setappdata(handles.root, 'last_opened_folder', '');
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes main wait for user response (see UIRESUME)
% uiwait(handles.root);
% --- Outputs from this function are returned to the command line.
function varargout = main_OutputFcn(hObject, eventdata, handles) %#ok<*INUSL>
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --------------------------------------------------------------------
function menu_file_Callback(hObject, eventdata, handles) %#ok<*DEFNU,*INUSD>
% hObject handle to menu_file (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes during object creation, after setting all properties.
function initial_solution_CreateFcn(hObject, eventdata, handles)
% hObject handle to initial_solution (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --------------------------------------------------------------------
function table_menu_Callback(hObject, eventdata, handles)
% hObject handle to table_menu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function table_add_row_Callback(hObject, eventdata, handles)
% hObject handle to table_add_row (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
add_row(handles);
% --- Executes when entered data in editable cell(s) in initial_solution.
function initial_solution_CellEditCallback(hObject, eventdata, handles)
% hObject handle to initial_solution (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.TABLE)
% Indices: row and column indices of the cell(s) edited
% PreviousData: previous data for the cell(s) edited
% EditData: string(s) entered by the user
% NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
% Error: error string when failed to convert EditData to appropriate value for Data
% handles structure with handles and user data (see GUIDATA)
replace_nan_initbl(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function delete_last_row_Callback(hObject, eventdata, handles)
% hObject handle to delete_last_row (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete_last_row(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function table_import_from_excel_Callback(hObject, eventdata, handles)
% hObject handle to table_import_from_excel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
import_initbl_excel(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function menu_edition_Callback(hObject, eventdata, handles)
% hObject handle to menu_edition (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_edition_cleantable_Callback(hObject, eventdata, handles)
% hObject handle to menu_edition_cleantable (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
clear_initialtable(handles, getappdata(handles.root, 'lang'), true);
% --------------------------------------------------------------------
function menu_file_new_Callback(hObject, eventdata, handles)
% hObject handle to menu_file_new (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
new_file(handles, getappdata(handles.root, 'lang'), true);
% --------------------------------------------------------------------
function menu_file_load_Callback(hObject, eventdata, handles)
% hObject handle to menu_file_load (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_project(handles, getappdata(handles.root, 'lang'));
% --- Executes during object creation, after setting all properties.
function initial_solution_table_title_CreateFcn(hObject, eventdata, handles)
% hObject handle to initial_solution_table_title (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --------------------------------------------------------------------
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_view_help_Callback(hObject, eventdata, handles)
% hObject handle to menu_view_help (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
manual;
% --------------------------------------------------------------------
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)
about(getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function menu_file_save_Callback(hObject, eventdata, handles)
% hObject handle to menu_file_save (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
save_project(handles, getappdata(handles.root, 'lang'), false);
% --------------------------------------------------------------------
function menu_file_save_as_Callback(hObject, eventdata, handles)
% hObject handle to menu_file_save_as (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
save_project(handles, getappdata(handles.root, 'lang'), true);
% --------------------------------------------------------------------
function menu_file_close_Callback(hObject, eventdata, handles)
% hObject handle to menu_file_close (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
doclose = close_app(handles, getappdata(handles.root, 'lang'));
if doclose
close all;
end
% --- Executes on button press in btn_opendispersion.
function btn_opendispersion_Callback(hObject, eventdata, handles)
% hObject handle to btn_opendispersion (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_dispersion_file(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function panel_dispersion_file_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to panel_dispersion_file (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on selection change in unit_h.
function unit_h_Callback(hObject, eventdata, handles)
% hObject handle to unit_h (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns unit_h contents as cell array
% contents{get(hObject,'Value')} returns selected item from unit_h
% --- Executes during object creation, after setting all properties.
function unit_h_CreateFcn(hObject, eventdata, handles)
% hObject handle to unit_h (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in unit_vsvp.
function unit_vsvp_Callback(hObject, eventdata, handles)
% hObject handle to unit_vsvp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns unit_vsvp contents as cell array
% contents{get(hObject,'Value')} returns selected item from unit_vsvp
% --- Executes during object creation, after setting all properties.
function unit_vsvp_CreateFcn(hObject, eventdata, handles)
% hObject handle to unit_vsvp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in unit_vr.
function unit_vr_Callback(hObject, eventdata, handles)
% hObject handle to unit_vr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns unit_vr contents as cell array
% contents{get(hObject,'Value')} returns selected item from unit_vr
% --- Executes during object creation, after setting all properties.
function unit_vr_CreateFcn(hObject, eventdata, handles)
% hObject handle to unit_vr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in unit_rho.
function unit_rho_Callback(hObject, eventdata, handles)
% hObject handle to unit_rho (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns unit_rho contents as cell array
% contents{get(hObject,'Value')} returns selected item from unit_rho
% --- Executes during object creation, after setting all properties.
function unit_rho_CreateFcn(hObject, eventdata, handles)
% hObject handle to unit_rho (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on mouse press over axes background.
function plt_dispersion_file_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to plt_dispersion_file (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function disp_plt_viewlarger_Callback(hObject, eventdata, handles)
% hObject handle to disp_plt_viewlarger (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
plot_large_dispcurv(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function dispersion_curve_menu_Callback(hObject, eventdata, handles)
% hObject handle to dispersion_curve_menu (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 start_button.
function start_button_Callback(hObject, eventdata, handles)
% hObject handle to start_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
start_inversion(handles, hObject, getappdata(handles.root, 'lang'));
function param_inv_sigma_Callback(hObject, eventdata, handles)
% hObject handle to param_inv_sigma (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_inv_sigma as text
% str2double(get(hObject,'String')) returns contents of param_inv_sigma as a double
% --- Executes during object creation, after setting all properties.
function param_inv_sigma_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_inv_sigma (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function param_inv_mu_Callback(hObject, eventdata, handles)
% hObject handle to param_inv_mu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_inv_mu as text
% str2double(get(hObject,'String')) returns contents of param_inv_mu as a double
% --- Executes during object creation, after setting all properties.
function param_inv_mu_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_inv_mu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function param_maxiter_Callback(hObject, eventdata, handles)
% hObject handle to param_maxiter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_maxiter as text
% str2double(get(hObject,'String')) returns contents of param_maxiter as a double
% --- Executes during object creation, after setting all properties.
function param_maxiter_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_maxiter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function param_tolvs_Callback(hObject, eventdata, handles)
% hObject handle to param_tolvs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_tolvs as text
% str2double(get(hObject,'String')) returns contents of param_tolvs as a double
% --- Executes during object creation, after setting all properties.
function param_tolvs_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_tolvs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in view_sol_plot.
function view_sol_plot_Callback(hObject, eventdata, handles)
% hObject handle to view_sol_plot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
show_plots(handles, getappdata(handles.root, 'lang'));
% --- Executes on button press in export_results.
function export_results_Callback(hObject, eventdata, handles)
% hObject handle to export_results (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
export_results(handles, hObject, getappdata(handles.root, 'lang'));
% --- Executes on key press with focus on param_inv_sigma and none of its controls.
function param_inv_sigma_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to param_inv_sigma (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over param_inv_sigma.
function param_inv_sigma_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to param_inv_sigma (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over param_inv_mu.
function param_inv_mu_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to param_inv_mu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on key press with focus on param_inv_mu and none of its controls.
function param_inv_mu_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to param_inv_mu (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over param_maxiter.
function param_maxiter_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to param_maxiter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on key press with focus on param_maxiter and none of its controls.
function param_maxiter_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to param_maxiter (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over param_tolvs.
function param_tolvs_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to param_tolvs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on key press with focus on param_tolvs and none of its controls.
function param_tolvs_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to param_tolvs (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over btn_opendispersion.
function btn_opendispersion_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to btn_opendispersion (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on key press with focus on btn_opendispersion and none of its controls.
function btn_opendispersion_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to btn_opendispersion (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% --- Executes when selected cell(s) is changed in initial_solution.
function initial_solution_CellSelectionCallback(hObject, eventdata, handles)
% hObject handle to initial_solution (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.TABLE)
% Indices: row and column indices of the cell(s) currently selecteds
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_import_table_from_excel_Callback(hObject, eventdata, handles)
% hObject handle to menu_import_table_from_excel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
import_initbl_excel(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function menu_add_row_table_Callback(hObject, eventdata, handles)
% hObject handle to menu_add_row_table (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
add_row(handles);
% --------------------------------------------------------------------
function menu_delete_row_table_Callback(hObject, eventdata, handles)
% hObject handle to menu_delete_row_table (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete_last_row(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function menu_edit_import_Callback(hObject, eventdata, handles)
% hObject handle to menu_edit_import (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_import_dispersion_file_Callback(hObject, eventdata, handles)
% hObject handle to menu_import_dispersion_file (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_dispersion_file(handles, getappdata(handles.root, 'lang'));
% --------------------------------------------------------------------
function menu_clean_initial_invparam_Callback(hObject, eventdata, handles)
% hObject handle to menu_clean_initial_invparam (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
clear_invparam(handles);
% --------------------------------------------------------------------
function menu_preferences_Callback(hObject, eventdata, handles)
% hObject handle to menu_preferences (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_cfg_app_Callback(hObject, eventdata, handles)
% hObject handle to menu_cfg_app (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get lang variable
lang = getappdata(handles.root, 'lang');
% Check if gui dir exist, if not a message error is displayed
if exist('gui', 'dir')
cfg_app(lang, 'main', handles);
else
disp_error(handles, lang, 128);
end
% --------------------------------------------------------------------
function menu_cfg_plot_Callback(hObject, eventdata, handles)
% hObject handle to menu_cfg_plot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_cfg_inversion_Callback(hObject, eventdata, handles)
% hObject handle to menu_cfg_inversion (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get lang variable
lang = getappdata(handles.root, 'lang');
% Check if gui dir exist, if not a message error is displayed
if exist('gui', 'dir')
cfg_inv(lang, 'main', handles.root);
else
disp_error(handles, lang, 128);
end
% --------------------------------------------------------------------
function menu_cfg_solution_Callback(hObject, eventdata, handles)
% hObject handle to menu_cfg_solution (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get lang variable
lang = getappdata(handles.root, 'lang');
% Check if gui dir exist, if not a message error is displayed
if exist('gui', 'dir')
cfg_sol(lang, 'main', handles.root);
else
disp_error(handles, lang, 128);
end
% --------------------------------------------------------------------
function dispersion_plt_viewtable_Callback(hObject, eventdata, handles)
% hObject handle to dispersion_plt_viewtable (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get lang variable
lang = getappdata(handles.root, 'lang');
if getappdata(handles.root, 'dispersion_ok')
view_disp_table(lang, 'main', handles.root);
end
|
github
|
UGM-Geofisika/Dispersion_Inversion-master
|
cfg_sol.m
|
.m
|
Dispersion_Inversion-master/gui/cfg_sol.m
| 9,758 |
utf_8
|
c33866390ebc4a79a24b23945faa1e47
|
function varargout = cfg_sol(varargin)
% ROOT MATLAB code for root.fig
% ROOT, by itself, creates a new ROOT or raises the existing
% singleton*.
%
% H = ROOT returns the handle to a new ROOT or the handle to
% the existing singleton*.
%
% ROOT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in ROOT.M with the given input arguments.
%
% ROOT('Property','Value',...) creates a new ROOT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before cfg_sol_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to cfg_sol_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 root
% Last Modified by GUIDE v2.5 27-Jan-2017 20:27:57
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @cfg_sol_OpeningFcn, ...
'gui_OutputFcn', @cfg_sol_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 root is made visible.
function cfg_sol_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>
% 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 root (see VARARGIN)
% Check if application is opened from main
if ~ (length(varargin)==3 && strcmp(varargin{2}, 'main'))
close;
end
% Set main variables
lang = varargin{1}; %#ok<*NASGU>
setappdata(handles.root, 'lang', lang);
setappdata(handles.root, 'main_handles', varargin{3});
% Set app strings
set(handles.root, 'Name', lang{129});
set_lang_string(handles.btn_save, lang{20}, 'string');
set_lang_string(handles.btn_close, lang{147}, 'string');
set_lang_string(handles.text_comparision, lang{132}, 'string');
set_lang_string(handles.text_shear, lang{133}, 'string');
set_lang_string(handles.text_iteration, lang{134}, 'string');
set_lang_string(handles.text_shear_comparision, lang{140}, 'string');
% Import config
config_solution;
config_app;
% Set config values
if show_dispersion_comparision
set(handles.cfg_comparision, 'Value', 1.0);
end
if show_shear_velocity_plot
set(handles.cfg_shear, 'Value', 1.0);
end
if show_dispersion_iterations
set(handles.cfg_iteration, 'Value', 1.0);
end
if show_shear_velocity_comparision
set(handles.cfg_comparision_shear, 'Value', 1.0);
end
% Save configs
setappdata(handles.root, 'gui_sound', gui_sound_enabled);
% Center window
movegui(gcf, 'center');
% Choose default command line output for root
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes root wait for user response (see UIRESUME)
% uiwait(handles.root);
% --- Outputs from this function are returned to the command line.
function varargout = cfg_sol_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in conf_lang.
function conf_lang_Callback(hObject, eventdata, handles)
% hObject handle to conf_lang (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns conf_lang contents as cell array
% contents{get(hObject,'Value')} returns selected item from conf_lang
% --- Executes during object creation, after setting all properties.
function conf_lang_CreateFcn(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>
% hObject handle to conf_lang (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in btn_save.
function btn_save_Callback(hObject, eventdata, handles)
% hObject handle to btn_save (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get lang
lang = getappdata(handles.root, 'lang');
% Get original handles
root_handles = getappdata(handles.root, 'main_handles');
% Import config
config_solution;
% Get configs
comparision = get(handles.cfg_comparision, 'Value');
shear = get(handles.cfg_shear, 'Value');
iteration = get(handles.cfg_iteration, 'Value');
shear_comparision = get(handles.cfg_comparision_shear, 'Value');
% Check if something changed
if (comparision == show_dispersion_comparision) && (shear == show_shear_velocity_plot) && ...
(show_dispersion_iterations == iteration) && (shear_comparision == show_shear_velocity_comparision)
else
% Set config strings
if comparision
str_comparision = 'show_dispersion_comparision = true;';
else
str_comparision = 'show_dispersion_comparision = false;';
end
if shear
str_shear = 'show_shear_velocity_plot = true;';
else
str_shear = 'show_shear_velocity_plot = false;';
end
if iteration
str_iteration = 'show_dispersion_iterations = true;';
else
str_iteration = 'show_dispersion_iterations = false;';
end
if shear_comparision
str_shear_comparision = 'show_shear_velocity_comparision = true;';
else
str_shear_comparision = 'show_shear_velocity_comparision = false;';
end
% Save config file
conf_file = fopen('gui/config_solution.m', 'wt');
write_conf_header(conf_file, ' SOLUTION CONFIGURATION', ' Configures solution behaviour.');
fprintf(conf_file, '%s\n', '% Show Calculated vs Experimental dispersion curve');
fprintf(conf_file, '%s\n\n', str_comparision);
fprintf(conf_file, '%s\n', '% Show Shear velocity on depth plot');
fprintf(conf_file, '%s\n\n', str_shear);
fprintf(conf_file, '%s\n', '% Show Calculated dispersion - iteration changes');
fprintf(conf_file, '%s\n\n', str_iteration);
fprintf(conf_file, '%s\n', '% Show shear velocity comparision');
fprintf(conf_file, '%s\n\n', str_shear_comparision);
fclose(conf_file);
% Set changes
setappdata(root_handles, 'show_dispersion_comparision', comparision);
setappdata(root_handles, 'show_shear_velocity_plot', shear);
setappdata(root_handles, 'show_dispersion_iterations', iteration);
setappdata(root_handles, 'show_shear_velocity_comparision', shear_comparision);
end
close;
% --- Executes on button press in btn_close.
function btn_close_Callback(hObject, eventdata, handles)
% hObject handle to btn_close (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close;
% --- Executes on button press in cfg_shear.
function cfg_shear_Callback(hObject, eventdata, handles)
% hObject handle to cfg_shear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_shear
% --- Executes on button press in cfg_delete_inv_entry.
function cfg_delete_inv_entry_Callback(hObject, eventdata, handles)
% hObject handle to cfg_delete_inv_entry (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_delete_inv_entry
% --- Executes on button press in cfg_comparision.
function cfg_comparision_Callback(hObject, eventdata, handles)
% hObject handle to cfg_comparision (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_comparision
% --- Executes on button press in cfg_iteration.
function cfg_iteration_Callback(hObject, eventdata, handles)
% hObject handle to cfg_iteration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_iteration
% --- Executes on button press in cfg_comparision_shear.
function cfg_comparision_shear_Callback(hObject, eventdata, handles)
% hObject handle to cfg_comparision_shear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_comparision_shear
|
github
|
UGM-Geofisika/Dispersion_Inversion-master
|
view_disp_table.m
|
.m
|
Dispersion_Inversion-master/gui/view_disp_table.m
| 3,934 |
utf_8
|
d795f65e03e1977c37b975f14f367207
|
function varargout = view_disp_table(varargin)
% VIEW_DISPERSION_TABLE MATLAB code for view_disp_table.fig
% VIEW_DISPERSION_TABLE, by itself, creates a new VIEW_DISPERSION_TABLE or raises the existing
% singleton*.
%
% H = VIEW_DISPERSION_TABLE returns the handle to a new VIEW_DISPERSION_TABLE or the handle to
% the existing singleton*.
%
% VIEW_DISPERSION_TABLE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in VIEW_DISPERSION_TABLE.M with the given input arguments.
%
% VIEW_DISPERSION_TABLE('Property','Value',...) creates a new VIEW_DISPERSION_TABLE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before view_dispersion_table_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to view_dispersion_table_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 view_dispersion_table
% Last Modified by GUIDE v2.5 09-Feb-2017 16:24:00
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @view_dispersion_table_OpeningFcn, ...
'gui_OutputFcn', @view_dispersion_table_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 view_dispersion_table is made visible.
function view_dispersion_table_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 view_dispersion_table (see VARARGIN)
% Choose default command line output for view_dispersion_table
handles.output = hObject;
% Check if application is opened from main
if ~(length(varargin) == 3 && strcmp(varargin{2}, 'main'))
close;
end
% Set main variables
lang = varargin{1}; %#ok<*NASGU>
setappdata(handles.root, 'lang', lang);
setappdata(handles.root, 'main_handles', varargin{3});
% Set app lang
set(handles.root, 'Name', lang{146});
% Set table
freq = getappdata(varargin{3}, 'disp_freq');
vrexp = getappdata(varargin{3}, 'disp_vrexp');
[nCols, ~] = size(vrexp);
% If data exists
if nCols ~= 0
% Create new cell structure
tabl = cell(nCols, 2);
tabl_nom = cell(nCols, 1);
% Copy data to new cell structures
for i = 1:nCols
tabl{i, 1} = freq(i);
tabl{i, 2} = vrexp(i);
tabl_nom{i} = strcat('f', num2str(i));
end
% Store data to table object
set(handles.table, 'Data', tabl);
set(handles.table, 'RowName', tabl_nom);
else
close;
end
% Center window
movegui(gcf, 'center');
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes view_dispersion_table wait for user response (see UIRESUME)
% uiwait(handles.root);
% --- Outputs from this function are returned to the command line.
function varargout = view_dispersion_table_OutputFcn(hObject, eventdata, handles) %#ok<*INUSL>
% 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
|
UGM-Geofisika/Dispersion_Inversion-master
|
manual.m
|
.m
|
Dispersion_Inversion-master/gui/manual.m
| 2,812 |
utf_8
|
547b164df037a6ccb4ebc0699cc92fd3
|
function varargout = manual(varargin)
% MANUAL MATLAB code for manual.fig
% MANUAL, by itself, creates a new MANUAL or raises the existing
% singleton*.
%
% H = MANUAL returns the handle to a new MANUAL or the handle to
% the existing singleton*.
%
% MANUAL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MANUAL.M with the given input arguments.
%
% MANUAL('Property','Value',...) creates a new MANUAL or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before manual_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to manual_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 manual
% Last Modified by GUIDE v2.5 26-Jan-2017 09:57:58
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @manual_OpeningFcn, ...
'gui_OutputFcn', @manual_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 manual is made visible.
function manual_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>
% 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 manual (see VARARGIN)
% Choose default command line output for manual
handles.output = hObject;
% Center window
movegui(gcf, 'center');
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes manual wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = manual_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
|
UGM-Geofisika/Dispersion_Inversion-master
|
cfg_inv.m
|
.m
|
Dispersion_Inversion-master/gui/cfg_inv.m
| 12,746 |
utf_8
|
5d47aac8bf783746377d2552555b7bec
|
function varargout = cfg_inv(varargin)
% ROOT MATLAB code for root.fig
% ROOT, by itself, creates a new ROOT or raises the existing
% singleton*.
%
% H = ROOT returns the handle to a new ROOT or the handle to
% the existing singleton*.
%
% ROOT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in ROOT.M with the given input arguments.
%
% ROOT('Property','Value',...) creates a new ROOT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before cfg_inv_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to cfg_inv_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 root
% Last Modified by GUIDE v2.5 27-Jan-2017 19:50:35
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @cfg_inv_OpeningFcn, ...
'gui_OutputFcn', @cfg_inv_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 root is made visible.
function cfg_inv_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>
% 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 root (see VARARGIN)
% Check if application is opened from main
if ~ (length(varargin)==3 && strcmp(varargin{2}, 'main'))
close;
end
% Set main variables
lang = varargin{1}; %#ok<*NASGU>
setappdata(handles.root, 'lang', lang);
setappdata(handles.root, 'main_handles', varargin{3});
% Set app strings
set(handles.root, 'Name', lang{130});
set(handles.panel_initialparams, 'Title', lang{135});
set_lang_string(handles.btn_save, lang{20}, 'string');
set_lang_string(handles.btn_close, lang{147}, 'string');
set(handles.text_mu, 'String', lang{136});
set(handles.text_sigma, 'String', lang{137});
set(handles.text_maxiter, 'String', lang{138});
set(handles.text_tolvs, 'String', lang{139});
% Import config
config_app;
config_inverse;
% Save configs
setappdata(handles.root, 'delete_entry_if_invalid', delete_entry_if_invalid);
setappdata(handles.root, 'gui_sound', gui_sound_enabled);
% Set initial configuration
set(handles.param_inv_mu, 'String', inv_mu);
set(handles.param_inv_sigma, 'String', inv_sigma);
set(handles.param_maxiter, 'String', inv_maxiter);
set(handles.param_tolvs, 'String', inv_tol_vs);
% Center window
movegui(gcf, 'center');
% Choose default command line output for root
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes root wait for user response (see UIRESUME)
% uiwait(handles.root);
% --- Outputs from this function are returned to the command line.
function varargout = cfg_inv_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in conf_lang.
function conf_lang_Callback(hObject, eventdata, handles)
% hObject handle to conf_lang (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns conf_lang contents as cell array
% contents{get(hObject,'Value')} returns selected item from conf_lang
% --- Executes during object creation, after setting all properties.
function conf_lang_CreateFcn(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>
% hObject handle to conf_lang (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in btn_save.
function btn_save_Callback(hObject, eventdata, handles)
% hObject handle to btn_save (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get lang
lang = getappdata(handles.root, 'lang');
% Get original handles
root_handles = getappdata(handles.root, 'main_handles');
% Import config
config_inverse;
% Check entry status
status = check_inv_parameters(handles, lang, true);
if status
sigma = get(handles.param_inv_sigma, 'string');
mu = get(handles.param_inv_mu, 'string');
maxiter = get(handles.param_maxiter, 'string');
tol_vs = get(handles.param_tolvs, 'string');
else
return
end
% Check if something changed
if (str2double(sigma) == inv_sigma) && (str2double(maxiter) == inv_maxiter) && ...
(str2double(mu) == inv_mu) && (inv_tol_vs == str2double(tol_vs))
else
% Create strings
str_maxiter = sprintf('inv_maxiter = %s;', maxiter);
str_mu = sprintf('inv_mu = %s;', mu);
str_sigma = sprintf('inv_sigma = %s;', sigma);
str_tolvs = sprintf('inv_tol_vs = %s;', tol_vs);
% Save config file
conf_file = fopen('gui/config_inverse.m', 'wt');
write_conf_header(conf_file, ' INVERSE MATLAB CONFIGURATION', ' Set configurations used by mat_inverse libraries.');
fprintf(conf_file, '%s\n', '% Maximum number of iterations, used by mat_inverse');
fprintf(conf_file, '%s\n\n', str_maxiter);
fprintf(conf_file, '%s\n', '% Mu coefficient, mat_inverse');
fprintf(conf_file, '%s\n\n', str_mu);
fprintf(conf_file, '%s\n', '% Vs tolerance error, mat_inverse');
fprintf(conf_file, '%s\n\n', str_tolvs);
fprintf(conf_file, '%s\n', '% Sigma, mat_inverse');
fprintf(conf_file, '%s\n\n', str_sigma);
fclose(conf_file);
% Set inversion config
sigma = str2double(sigma);
mu = str2double(mu);
maxiter = str2double(maxiter);
tol_vs = str2double(tol_vs);
setappdata(root_handles, 'cgf_sigma', sigma);
setappdata(root_handles, 'cgf_mu', mu);
setappdata(root_handles, 'cgf_maxiter', maxiter);
setappdata(root_handles, 'cgf_tolvs', tol_vs);
end
close;
% --- Executes on button press in btn_close.
function btn_close_Callback(hObject, eventdata, handles)
% hObject handle to btn_close (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close;
% --- Executes on button press in cfg_shear.
function cfg_shear_Callback(hObject, eventdata, handles)
% hObject handle to cfg_shear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_shear
% --- Executes on button press in cfg_delete_inv_entry.
function cfg_delete_inv_entry_Callback(hObject, eventdata, handles)
% hObject handle to cfg_delete_inv_entry (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_delete_inv_entry
% --- Executes on button press in cfg_comparision.
function cfg_comparision_Callback(hObject, eventdata, handles)
% hObject handle to cfg_comparision (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_comparision
% --- Executes on button press in cfg_iteration.
function cfg_iteration_Callback(hObject, eventdata, handles)
% hObject handle to cfg_iteration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of cfg_iteration
function param_inv_mu_Callback(hObject, eventdata, handles)
% hObject handle to param_inv_mu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_inv_mu as text
% str2double(get(hObject,'String')) returns contents of param_inv_mu as a double
% --- Executes during object creation, after setting all properties.
function param_inv_mu_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_inv_mu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function param_inv_sigma_Callback(hObject, eventdata, handles)
% hObject handle to param_inv_sigma (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_inv_sigma as text
% str2double(get(hObject,'String')) returns contents of param_inv_sigma as a double
% --- Executes during object creation, after setting all properties.
function param_inv_sigma_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_inv_sigma (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function param_maxiter_Callback(hObject, eventdata, handles)
% hObject handle to param_maxiter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_maxiter as text
% str2double(get(hObject,'String')) returns contents of param_maxiter as a double
% --- Executes during object creation, after setting all properties.
function param_maxiter_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_maxiter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function param_tolvs_Callback(hObject, eventdata, handles)
% hObject handle to param_tolvs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of param_tolvs as text
% str2double(get(hObject,'String')) returns contents of param_tolvs as a double
% --- Executes during object creation, after setting all properties.
function param_tolvs_CreateFcn(hObject, eventdata, handles)
% hObject handle to param_tolvs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
|
github
|
UGM-Geofisika/Dispersion_Inversion-master
|
mat_inverse.m
|
.m
|
Dispersion_Inversion-master/bin/mat_inverse.m
| 2,755 |
utf_8
|
ecba5e9d7c128ae9a9c8c0df5527cdcd
|
function [niter, vr_iter, vp_iter, vs_iter, dns_iter] = mat_inverse(freq, vr_exp, ...
sigma, thk, vp, vs, dns, maxiter, mu, tol_vs, gui, object, msg)
% input:
% 1. dispersion curve
% freq, vr_exp, sigma
% 2. initial model
% thk, vp, vs, dns
% 3. parameters control the inversion
% maxiter, mu, tol_vs (change in vs)
% 4. GUI parameters
% gui (true/false), object, label, msg (message to show, as %d/%d)
% Modification history:
% 01/19/2017: Pablo Pizarro (UChile)
% (1) Deleted files related to Love wave
% 01/20/2017: Pablo Pizarro (UChile)
% (1) Add GUI support
% (2) Iteration number is displayed on GUI
% (3) Some statuses are displayed on GUI
% Number of layers
nl = length(thk);
% Weight matrix
w = diag(1./sigma);
% Second derivative
delta = curv(nl, nl+1);
L = delta;
rms = zeros(maxiter, 1);
% Initialize intial guess
m0 = vs;
vp0 = vp;
vs0 = vs;
dns0 = dns;
% Initialize interation variables
vp_iter = zeros(nl+1, maxiter);
vs_iter = zeros(nl+1, maxiter);
dns_iter = zeros(nl+1, maxiter);
vr_iter = zeros(length(freq), maxiter);
% Check if gui parameters is defined
if ~exist('gui', 'var')
gui = false;
end
for i = 1:maxiter
% If GUI
if gui
pause(0.01);
set(object, 'string', sprintf(msg, i, maxiter));
end
% Calculate theoretical phase velocity and partial derivatives
% warning: presently the code only handle 1 type of dispersion!
[vr, dvrvs, ~] = mat_disperse(thk, dns0, vp0, vs0, freq);
jac = real(squeeze(dvrvs)); % jac = [real(squeeze(dvrvs)) real(squeeze(dvrrho))];
% Calculate the rms error
error = w * (vr - vr_exp);
rms(i) = sqrt(mean(error .^ 2));
% Least square inversion
wjac = w * jac;
b = w * (vr_exp - vr + jac * m0);
m1 = (wjac' * wjac + mu ^ 2 * (L' * L)) \ (wjac' * b);
% Evaluate new model
vs1 = m1(1:nl+1);
vp1 = vp;
dns1 = dns; % dns1 = m1(nl+2:nl+2+nl);
vr = mat_disperse(thk, dns1, vp1, vs1, freq);
error1 = w * (vr - vr_exp);
rms1 = sqrt(mean(error1 .^ 2));
% Store the models
vp_iter(:, i) = vp1;
vs_iter(:, i) = vs1;
dns_iter(:, i) = dns1;
vr_iter(:, i) = vr(:);
% Check for convergence, only check vs ?
diff_vs = vs1 - vs0;
rms_vs_change = sqrt(mean(diff_vs .^ 2));
if rms_vs_change < tol_vs || rms1 <= 1
break
end
m0 = m1;
dns0 = dns1;
vp0 = vp1;
vs0 = vs1;
end
niter = i;
end
% Curvature matrix for regularization
function delta = curv(m, ~)
delta = diag(ones(1, m), 0) + diag(-2*ones(1, m-1), 1) + diag(ones(1, m-2), 2);
tmp = zeros(m, 1);
tmp(m) = - 1;
tmp(m - 1) = 1;
delta = [delta, tmp];
end
|
github
|
foss-for-synopsys-dwc-arc-processors/synopsys-caffe-main
|
classification_demo.m
|
.m
|
synopsys-caffe-main/matlab/demo/classification_demo.m
| 5,466 |
utf_8
|
45745fb7cfe37ef723c307dfa06f1b97
|
function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to the Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% and what versions are installed.
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab code for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to your Matlab search PATH in order to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github
|
foss-for-synopsys-dwc-arc-processors/synopsys-caffe-main
|
MyVOCevalseg.m
|
.m
|
synopsys-caffe-main/matlab/my_script/MyVOCevalseg.m
| 4,471 |
utf_8
|
f0b406d4e609f1cc3d3694948aeceb67
|
%VOCEVALSEG Evaluates a set of segmentation results.
% VOCEVALSEG(VOCopts,ID); prints out the per class and overall
% segmentation accuracies. Accuracies are given using the intersection/union
% metric:
% true positives / (true positives + false positives + false negatives)
%
% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class
% percentage ACCURACIES, the average accuracy AVACC and the confusion
% matrix CONF.
%
% [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns
% the unnormalised confusion matrix, which contains raw pixel counts.
function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id)
% image test set
[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');
% number of labels = number of classes plus one for the background
num = VOCopts.nclasses+1;
confcounts = zeros(num);
count=0;
num_missing_img = 0;
tic;
for i=1:length(gtids)
% display progress
if toc>1
fprintf('test confusion: %d/%d\n',i,length(gtids));
drawnow;
tic;
end
imname = gtids{i};
% ground truth label file
gtfile = sprintf(VOCopts.seg.clsimgpath,imname);
[gtim,map] = imread(gtfile);
gtim = double(gtim);
% results file
resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);
try
[resim,map] = imread(resfile);
catch err
num_missing_img = num_missing_img + 1;
%fprintf(1, 'Fail to read %s\n', resfile);
continue;
end
resim = double(resim);
% Check validity of results image
maxlabel = max(resim(:));
if (maxlabel>VOCopts.nclasses),
error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);
end
szgtim = size(gtim); szresim = size(resim);
if any(szgtim~=szresim)
error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));
end
%pixel locations to include in computation
locs = gtim<255;
% joint histogram
sumim = 1+gtim+resim*num;
hs = histc(sumim(locs),1:num*num);
count = count + numel(find(locs));
confcounts(:) = confcounts(:) + hs(:);
end
if (num_missing_img > 0)
fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img);
end
% confusion matrix - first index is true label, second is inferred label
%conf = zeros(num);
conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]);
rawcounts = confcounts;
% Pixel Accuracy
overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));
fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc);
% Class Accuracy
class_acc = zeros(1, num);
class_count = 0;
fprintf('Accuracy for each class (pixel accuracy)\n');
for i = 1 : num
denom = sum(confcounts(i, :));
if (denom == 0)
denom = 1;
end
class_acc(i) = 100 * confcounts(i, i) / denom;
if i == 1
clname = 'background';
else
clname = VOCopts.classes{i-1};
end
if ~strcmp(clname, 'void')
class_count = class_count + 1;
fprintf(' %14s: %6.3f%%\n', clname, class_acc(i));
end
end
fprintf('-------------------------\n');
avg_class_acc = sum(class_acc) / class_count;
fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc);
% Pixel IOU
accuracies = zeros(VOCopts.nclasses,1);
fprintf('Accuracy for each class (intersection/union measure)\n');
real_class_count = 0;
for j=1:num
gtj=sum(confcounts(j,:));
resj=sum(confcounts(:,j));
gtjresj=confcounts(j,j);
% The accuracy is: true positive / (true positive + false positive + false negative)
% which is equivalent to the following percentage:
denom = (gtj+resj-gtjresj);
if denom == 0
denom = 1;
end
accuracies(j)=100*gtjresj/denom;
clname = 'background';
if (j>1), clname = VOCopts.classes{j-1};end;
if ~strcmp(clname, 'void')
real_class_count = real_class_count + 1;
else
if denom ~= 1
fprintf(1, 'WARNING: this void class has denom = %d\n', denom);
end
end
if ~strcmp(clname, 'void')
fprintf(' %14s: %6.3f%%\n',clname,accuracies(j));
end
end
%accuracies = accuracies(1:end);
%avacc = mean(accuracies);
avacc = sum(accuracies) / real_class_count;
fprintf('-------------------------\n');
fprintf('Average accuracy: %6.3f%%\n',avacc);
|
github
|
foss-for-synopsys-dwc-arc-processors/synopsys-caffe-main
|
MyVOCevalsegBoundary.m
|
.m
|
synopsys-caffe-main/matlab/my_script/MyVOCevalsegBoundary.m
| 4,279 |
utf_8
|
704c57ab30eda1a0f001187608d3c786
|
%VOCEVALSEG Evaluates a set of segmentation results.
% VOCEVALSEG(VOCopts,ID); prints out the per class and overall
% segmentation accuracies. Accuracies are given using the intersection/union
% metric:
% true positives / (true positives + false positives + false negatives)
%
% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class
% percentage ACCURACIES, the average accuracy AVACC and the confusion
% matrix CONF.
%
% [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns
% the unnormalised confusion matrix, which contains raw pixel counts.
function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w)
% get structural element
st_w = 2*w + 1;
se = strel('square', st_w);
% image test set
fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset);
fid = fopen(fn, 'r');
gtids = textscan(fid, '%s');
gtids = gtids{1};
fclose(fid);
%[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');
% number of labels = number of classes plus one for the background
num = VOCopts.nclasses+1;
confcounts = zeros(num);
count=0;
tic;
for i=1:length(gtids)
% display progress
if toc>1
fprintf('test confusion: %d/%d\n',i,length(gtids));
drawnow;
tic;
end
imname = gtids{i};
% ground truth label file
gtfile = sprintf(VOCopts.seg.clsimgpath,imname);
[gtim,map] = imread(gtfile);
gtim = double(gtim);
% results file
resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);
try
[resim,map] = imread(resfile);
catch err
fprintf(1, 'Fail to read %s\n', resfile);
continue;
end
resim = double(resim);
% Check validity of results image
maxlabel = max(resim(:));
if (maxlabel>VOCopts.nclasses),
error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);
end
szgtim = size(gtim); szresim = size(resim);
if any(szgtim~=szresim)
error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));
end
% dilate gt
binary_gt = gtim == 255;
dilate_gt = imdilate(binary_gt, se);
target_gt = dilate_gt & (gtim~=255);
%pixel locations to include in computation
locs = target_gt;
%locs = gtim<255;
% joint histogram
sumim = 1+gtim+resim*num;
hs = histc(sumim(locs),1:num*num);
count = count + numel(find(locs));
confcounts(:) = confcounts(:) + hs(:);
end
% confusion matrix - first index is true label, second is inferred label
%conf = zeros(num);
conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]);
rawcounts = confcounts;
% Pixel Accuracy
overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));
fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc);
% Class Accuracy
class_acc = zeros(1, num);
class_count = 0;
fprintf('Accuracy for each class (pixel accuracy)\n');
for i = 1 : num
denom = sum(confcounts(i, :));
if (denom == 0)
denom = 1;
else
class_count = class_count + 1;
end
class_acc(i) = 100 * confcounts(i, i) / denom;
if i == 1
clname = 'background';
else
clname = VOCopts.classes{i-1};
end
fprintf(' %14s: %6.3f%%\n', clname, class_acc(i));
end
fprintf('-------------------------\n');
avg_class_acc = sum(class_acc) / class_count;
fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc);
% Pixel IOU
accuracies = zeros(VOCopts.nclasses,1);
fprintf('Accuracy for each class (intersection/union measure)\n');
for j=1:num
gtj=sum(confcounts(j,:));
resj=sum(confcounts(:,j));
gtjresj=confcounts(j,j);
% The accuracy is: true positive / (true positive + false positive + false negative)
% which is equivalent to the following percentage:
accuracies(j)=100*gtjresj/(gtj+resj-gtjresj);
clname = 'background';
if (j>1), clname = VOCopts.classes{j-1};end;
fprintf(' %14s: %6.3f%%\n',clname,accuracies(j));
end
accuracies = accuracies(1:end);
avacc = mean(accuracies);
fprintf('-------------------------\n');
fprintf('Average accuracy: %6.3f%%\n',avacc);
|
github
|
raalf/VAP3-master
|
fcnXML2STRUCT.m
|
.m
|
VAP3-master/fcnXML2STRUCT.m
| 6,958 |
utf_8
|
f865267aab457943222a8412bb26b6a7
|
function [ s ] = fcnXML2STRUCT( file )
%Convert xml file into a MATLAB structure
% [ s ] = xml2struct( file )
%
% A file containing:
% <XMLname attrib1="Some value">
% <Element>Some text</Element>
% <DifferentElement attrib2="2">Some more text</Element>
% <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement>
% </XMLname>
%
% Will produce:
% s.XMLname.Attributes.attrib1 = "Some value";
% s.XMLname.Element.Text = "Some text";
% s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2";
% s.XMLname.DifferentElement{1}.Text = "Some more text";
% s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2";
% s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1";
% s.XMLname.DifferentElement{2}.Text = "Even more text";
%
% Please note that the following characters are substituted
% '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_'
%
% Written by W. Falkena, ASTI, TUDelft, 21-08-2010
% Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011
% Added CDATA support by I. Smirnov, 20-3-2012
%
% Modified by X. Mo, University of Wisconsin, 12-5-2012
if (nargin < 1)
clc;
help xml2struct
return
end
if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl')
% input is a java xml object
xDoc = file;
else
%check for existance
if (exist(file,'file') == 0)
%Perhaps the xml extension was omitted from the file name. Add the
%extension and try again.
if (isempty(strfind(file,'.xml')))
file = [file '.xml'];
end
if (exist(file,'file') == 0)
error(['The file ' file ' could not be found']);
end
end
%read the xml file
xDoc = xmlread(file);
end
%parse xDoc into a MATLAB structure
s = parseChildNodes(xDoc);
end
% ----- Subfunction parseChildNodes -----
function [children,ptext,textflag] = parseChildNodes(theNode)
% Recurse over node children.
children = struct;
ptext = struct; textflag = 'Text';
if hasChildNodes(theNode)
childNodes = getChildNodes(theNode);
numChildNodes = getLength(childNodes);
for count = 1:numChildNodes
theChild = item(childNodes,count-1);
[text,name,attr,childs,textflag] = getNodeData(theChild);
if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section'))
%XML allows the same elements to be defined multiple times,
%put each in a different cell
if (isfield(children,name))
if (~iscell(children.(name)))
%put existsing element into cell format
children.(name) = {children.(name)};
end
index = length(children.(name))+1;
%add new element
children.(name){index} = childs;
if(~isempty(fieldnames(text)))
children.(name){index} = text;
end
if(~isempty(attr))
children.(name){index}.('Attributes') = attr;
end
else
%add previously unknown (new) element to the structure
children.(name) = childs;
if(~isempty(text) && ~isempty(fieldnames(text)))
children.(name) = text;
end
if(~isempty(attr))
children.(name).('Attributes') = attr;
end
end
else
ptextflag = 'Text';
if (strcmp(name, '#cdata_dash_section'))
ptextflag = 'CDATA';
elseif (strcmp(name, '#comment'))
ptextflag = 'Comment';
end
%this is the text in an element (i.e., the parentNode)
if (~isempty(regexprep(text.(textflag),'[\s]*','')))
if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag)))
ptext.(ptextflag) = text.(textflag);
else
%what to do when element data is as follows:
%<element>Text <!--Comment--> More text</element>
%put the text in different cells:
% if (~iscell(ptext)) ptext = {ptext}; end
% ptext{length(ptext)+1} = text;
%just append the text
ptext.(ptextflag) = [ptext.(ptextflag) text.(textflag)];
end
end
end
end
end
end
% ----- Subfunction getNodeData -----
function [text,name,attr,childs,textflag] = getNodeData(theNode)
% Create structure of node info.
%make sure name is allowed as structure name
name = toCharArray(getNodeName(theNode))';
name = strrep(name, '-', '_dash_');
name = strrep(name, ':', '_colon_');
name = strrep(name, '.', '_dot_');
attr = parseAttributes(theNode);
if (isempty(fieldnames(attr)))
attr = [];
end
%parse child nodes
[childs,text,textflag] = parseChildNodes(theNode);
if (isempty(fieldnames(childs)) && isempty(fieldnames(text)))
%get the data of any childless nodes
% faster than if any(strcmp(methods(theNode), 'getData'))
% no need to try-catch (?)
% faster than text = char(getData(theNode));
text.(textflag) = toCharArray(getTextContent(theNode))';
end
end
% ----- Subfunction parseAttributes -----
function attributes = parseAttributes(theNode)
% Create attributes structure.
attributes = struct;
if hasAttributes(theNode)
theAttributes = getAttributes(theNode);
numAttributes = getLength(theAttributes);
for count = 1:numAttributes
%attrib = item(theAttributes,count-1);
%attr_name = regexprep(char(getName(attrib)),'[-:.]','_');
%attributes.(attr_name) = char(getValue(attrib));
%Suggestion of Adrian Wanner
str = toCharArray(toString(item(theAttributes,count-1)))';
k = strfind(str,'=');
attr_name = str(1:(k(1)-1));
attr_name = strrep(attr_name, '-', '_dash_');
attr_name = strrep(attr_name, ':', '_colon_');
attr_name = strrep(attr_name, '.', '_dot_');
attributes.(attr_name) = str((k(1)+2):(end-1));
end
end
end
|
github
|
raalf/VAP3-master
|
fcnPLOTCIRC.m
|
.m
|
VAP3-master/fcnPLOTCIRC.m
| 2,440 |
utf_8
|
e988613a8ca8bc1d1f6be5ec87a03277
|
function [] = fcnPLOTCIRC(valNELE, matDVE, matVLST, matCENTER, vecDVEROLL, vecDVEPITCH, vecDVEYAW, matCOEFF, ppa)
for i = 1:valNELE
corners = fcnGLOBSTAR(matVLST(matDVE(i,:),:) - matCENTER(i,:), repmat(vecDVEROLL(i),4,1), repmat(vecDVEPITCH(i),4,1), repmat(vecDVEYAW(i),4,1));
points = polygrid(corners(:,1), corners(:,2), ppa);
len = size(points,1);
% vort_p = fcnSTARGLOB([points(:,1) points(:,2) zeros(len,1)], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1)) + matCENTER(i,:);
% vort = fcnSTARGLOB([(2.*matCOEFF(i,4).*points(:,1) + matCOEFF(i,5)) (2.*matCOEFF(i,1).*points(:,2) + matCOEFF(i,2)) zeros(len,1)], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1));
% vort = fcnSTARGLOB([zeros(len,1) (2.*matCOEFF(i,1).*points(:,2) + matCOEFF(i,2)) zeros(len,1)], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1));
% % points(:,2) is eta in local, points(:,1) is xsi
% circ = matCOEFF(i,1).*points(:,2).^2 + matCOEFF(i,2).*points(:,2) + matCOEFF(i,3) + matCOEFF(i,4).*points(:,1).^2 + matCOEFF(i,5).*points(:,1) + matCOEFF(i,6);
circ = matCOEFF(i,3).*points(:,2).^2 + matCOEFF(i,2).*points(:,2) + matCOEFF(i,1);
len = size(circ,1);
tri = delaunay(points(:,1), points(:,2));
circ_glob = fcnSTARGLOB([points circ], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1));
circ_glob = circ_glob + matCENTER(i,:);
hold on
trisurf(tri, circ_glob(:,1), circ_glob(:,2), circ_glob(:,3),'edgealpha',0,'facealpha',0.8);
% quiver3(vort_p(:,1), vort_p(:,2), vort_p(:,3), vort(:,1), vort(:,2), vort(:,3))
hold off
end
function [inPoints] = polygrid( xv, yv, N)
%Find the bounding rectangle
lower_x = min(xv);
higher_x = max(xv);
lower_y = min(yv);
higher_y = max(yv);
%Create a grid of points within the bounding rectangle
inc_x = (higher_x - lower_x)/N;
inc_y = (higher_y - lower_y)/N;
interval_x = lower_x:inc_x:higher_x;
interval_y = lower_y:inc_y:higher_y;
[bigGridX, bigGridY] = meshgrid(interval_x, interval_y);
%Filter grid to get only points in polygon
[in,on] = inpolygon(bigGridX(:), bigGridY(:), xv, yv);
in = in | on;
%Return the co-ordinates of the points that are in the polygon
inPoints = [bigGridX(in), bigGridY(in)];
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.