├── Examples
├── VO2_Raman.mat
├── VO2_Raman.png
├── Er_PL_in_YSO.mat
├── Er_PL_in_YSO.png
├── Er_PL_in_YSO.m
└── VO2_Raman.m
├── @PeakFit
├── fngaussian.m
├── fnlorentzian.m
├── computearea.m
├── computewidth.m
├── computeheight.m
├── model.m
├── transformpolycoeff.m
├── findmaxima.m
├── disp.m
├── convertunit.m
├── fit.m
└── PeakFit.m
├── movmean (for MATLAB older than R2016a).m
├── README.md
└── LICENSE
/Examples/VO2_Raman.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heriantolim/PeakFit/HEAD/Examples/VO2_Raman.mat
--------------------------------------------------------------------------------
/Examples/VO2_Raman.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heriantolim/PeakFit/HEAD/Examples/VO2_Raman.png
--------------------------------------------------------------------------------
/Examples/Er_PL_in_YSO.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heriantolim/PeakFit/HEAD/Examples/Er_PL_in_YSO.mat
--------------------------------------------------------------------------------
/Examples/Er_PL_in_YSO.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/heriantolim/PeakFit/HEAD/Examples/Er_PL_in_YSO.png
--------------------------------------------------------------------------------
/@PeakFit/fngaussian.m:
--------------------------------------------------------------------------------
1 | function y = fngaussian(x, c, h, w)
2 | %% Gaussian function with center c, height h, and FWHM w
3 | %
4 | % Copyright: Herianto Lim (https://heriantolim.com)
5 | % Licensing: GNU General Public License v3.0
6 | % First created: 04/04/2013
7 | % Last modified: 04/04/2013
8 |
9 | y = h * exp(-4 * log(2) * (x - c).^2 / w^2);
10 |
11 | end
12 |
--------------------------------------------------------------------------------
/@PeakFit/fnlorentzian.m:
--------------------------------------------------------------------------------
1 | function y = fnlorentzian(x, c, h, w)
2 | %% Lorentzian function with center c, height h, and FWHM w
3 | %
4 | % Copyright: Herianto Lim (https://heriantolim.com)
5 | % Licensing: GNU General Public License v3.0
6 | % First created: 04/04/2013
7 | % Last modified: 04/04/2013
8 |
9 | y = h * (w / 2)^2 ./ ((x - c).^2 + (w / 2)^2);
10 |
11 | end
12 |
--------------------------------------------------------------------------------
/@PeakFit/computearea.m:
--------------------------------------------------------------------------------
1 | function area = computearea(peakShape, height, width)
2 | %% Compute Peak Area
3 | % area = PeakFit.computearea(peakShape, height, width) computes the area
4 | % of a peak function of the specified peakShape, given its heights and
5 | % widths.
6 | %
7 | % Copyright: Herianto Lim (https://heriantolim.com)
8 | % Licensing: GNU General Public License v3.0
9 | % First created: 25/03/2013
10 | % Last modified: 25/03/2013
11 |
12 | assert(isintegerscalar(peakShape), ...
13 | 'PeakFit:computearea:InvalidInput', ...
14 | 'Input to the peak shape must be an integer scalar.');
15 | assert(isrealarray(height) && isrealarray(width), ...
16 | 'PeakFit:computearea:InvalidInput', ...
17 | 'Input to the height and width must be arrays of real numbers.');
18 | assert(all(size(height) == size(width)), ...
19 | 'PeakFit:computearea:InvalidInput', ...
20 | 'The height and width arrays must have the same dimensions.');
21 |
22 | switch peakShape
23 | case 1
24 | area = pi / 2 * height .* width;
25 | case 2
26 | area = sqrt(pi / log(2)) / 2 * height .* width;
27 | otherwise
28 | error('PeakFit:computearea:UnexpectedInput', ...
29 | 'The specified peak shape is not recognized.');
30 | end
31 |
32 | end
33 |
--------------------------------------------------------------------------------
/@PeakFit/computewidth.m:
--------------------------------------------------------------------------------
1 | function width = computewidth(peakShape, area, height)
2 | %% Compute Peak Width
3 | % width = PeakFit.computewidth(peakShape, area, height) computes the width
4 | % of a peak function of the specified peakShape, given its area and
5 | % height.
6 | %
7 | % Copyright: Herianto Lim (https://heriantolim.com)
8 | % Licensing: GNU General Public License v3.0
9 | % First created: 25/03/2013
10 | % Last modified: 25/03/2013
11 |
12 | assert(isintegerscalar(peakShape), ...
13 | 'PeakFit:computewidth:InvalidInput', ...
14 | 'Input to the peak shape must be an integer scalar.');
15 | assert(isrealarray(area) && isrealarray(height), ...
16 | 'PeakFit:computewidth:InvalidInput', ...
17 | 'Input to the area and height must be arrays of real numbers.');
18 | assert(all(size(area) == size(height)), ...
19 | 'PeakFit:computewidth:InvalidInput', ...
20 | 'The area and height arrays must have the same dimensions.');
21 |
22 | switch peakShape
23 | case 1
24 | width = 2 / pi * area ./ height;
25 | case 2
26 | width = 2 / sqrt(pi / log(2)) * area ./ height;
27 | otherwise
28 | error('PeakFit:computewidth:UnexpectedInput', ...
29 | 'The specified peak shape is not recognized.');
30 | end
31 |
32 | end
33 |
--------------------------------------------------------------------------------
/@PeakFit/computeheight.m:
--------------------------------------------------------------------------------
1 | function height = computeheight(peakShape, area, width)
2 | %% Compute Peak Height
3 | % height = PeakFit.computeheight(peakShape, area, width) computes the
4 | % height of a peak function of the specified peakShape, given its areas
5 | % and widths.
6 | %
7 | % Copyright: Herianto Lim (https://heriantolim.com)
8 | % Licensing: GNU General Public License v3.0
9 | % First created: 25/03/2013
10 | % Last modified: 25/03/2013
11 |
12 | assert(isintegerscalar(peakShape), ...
13 | 'PeakFit:computeheight:InvalidInput', ...
14 | 'Input to the peak shape must be an integer scalar.');
15 | assert(isrealarray(area) && isrealarray(width), ...
16 | 'PeakFit:computeheight:InvalidInput', ...
17 | 'Input to the area and width must be arrays of real numbers.');
18 | assert(all(size(area) == size(width)), ...
19 | 'PeakFit:computeheight:InvalidInput', ...
20 | 'The area and width arrays must have the same dimensions.');
21 |
22 | switch peakShape
23 | case 1
24 | height = 2 / pi * area ./ width;
25 | case 2
26 | height = 2 / sqrt(pi / log(2)) * area ./ width;
27 | otherwise
28 | error('PeakFit:computeheight:UnexpectedInput', ...
29 | 'The specified peak shape is not recognized.');
30 | end
31 |
32 | end
33 |
--------------------------------------------------------------------------------
/movmean (for MATLAB older than R2016a).m:
--------------------------------------------------------------------------------
1 | function u = movmean(v, varargin)
2 | %% Moving Mean
3 | % This function is provided for backwards compatibility. It does the same
4 | % job as the builtin function, movmean, which was introduced in MATLAB
5 | % R2016a. It can be safely deleted on newer MATLAB.
6 | %
7 | % u = movmean(v) computes the simple moving average of the vector v using
8 | % sample width = 1.
9 | %
10 | % u = movmean(v,w) computes the simple moving average of the vector v
11 | % using sample width = w.
12 | %
13 | % Tested on:
14 | % - MATLAB R2013b
15 | % - MATLAB R2015b
16 | %
17 | % Copyright: Herianto Lim
18 | % https://heriantolim.com/
19 | % First created: 22/03/2013
20 | % Last modified: 20/10/2016
21 |
22 | %% Input Validation and Parsing
23 | assert(isvector(v) && isreal(v), ...
24 | 'Input to the sample vector must be a real vector.');
25 |
26 | if isempty(varargin)
27 | w = 1;
28 | elseif isscalar(varargin{1}) && isreal(varargin{1}) && varargin{1} >= 0
29 | w = varargin{1};
30 | else
31 | error('Input to the sample width must be a positive real scalar.');
32 | end
33 |
34 | %% Simple Moving Average
35 | u = v;
36 |
37 | if w == 0
38 | return
39 | end
40 |
41 | n = numel(v);
42 | w = ceil(w / 2);
43 |
44 | for i = 2:w
45 | u(i) = mean(v(1:2 * i - 1));
46 | u(n - i + 1) = mean(v(n - 2 * i + 2:n));
47 | end
48 |
49 | n1 = 1 + w;
50 | n2 = n - w;
51 |
52 | for i = n1:n2
53 | u(i) = mean(v(i - w:i + w));
54 | end
55 |
56 | end
57 |
--------------------------------------------------------------------------------
/Examples/Er_PL_in_YSO.m:
--------------------------------------------------------------------------------
1 | %% PeakFit Example #1: Er PL in YSO
2 | %
3 | % Copyright: Herianto Lim (https://heriantolim.com)
4 | % Licensing: GNU General Public License v3.0
5 | % First created: 28/10/2018
6 | % Last modified: 28/10/2018
7 |
8 | % Add the required packages using MatVerCon.
9 | % addpackage('MatCommon','MatGraphics','PeakFit');
10 |
11 | % Clear workspace variables.
12 | clear;
13 |
14 | % Load data. If fails, adjust the file path supplied to the argument.
15 | S = load('Er_PL_in_YSO.mat');
16 |
17 | % Perform Lorentzian peak fitting with default values.
18 | % The algorithm will attempt to find all the peaks in the spectrum.
19 | S.Fit = PeakFit(S.Data, 'PeakShape', 'Lorentzian');
20 |
21 | %% Plotting
22 | % Settings.
23 | Groot.usedefault();
24 | Groot.usedefault('latex', 8, .6);
25 | RESOLUTION = 300;
26 | AXES_SIZE = [12, 4];
27 | TICK_LENGTH = .2;
28 |
29 | % Plot data.
30 | xData = S.Fit.XData;
31 | yData = S.Fit.YData;
32 | xLim = S.Fit.Window;
33 | xModel = linspace(xLim(1), xLim(2), ceil(RESOLUTION / 2.54 * AXES_SIZE(1)));
34 | [yModel, yPeak, yBaseline] = S.Fit.model(xModel);
35 | yLim = [min(min(yData), min(yBaseline)), max(max(yData), max(yModel))];
36 |
37 | % Figure.
38 | fig = docfigure(AXES_SIZE);
39 |
40 | % Axes.
41 | pos = [0, 0, AXES_SIZE];
42 | ax = axes('Position', pos, 'XLim', xLim, 'YLim', yLim, 'YTickLabel', '');
43 | xlabel('Wavenumber (cm$^{-1}$)');
44 | ylabel('Intensity (arb. unit)');
45 | fixticklength(.2);
46 |
47 | % Plots.
48 | N = S.Fit.NumPeaks;
49 | h = plot(xData, yData, 'Color', 'b');
50 |
51 | for j = 1:N
52 | plot(xModel, yBaseline + yPeak{j}, 'Color', 'r', 'LineWidth', .3);
53 | end
54 |
55 | h(2) = plot(xModel, yModel, 'Color', 'g', 'LineWidth', .3);
56 |
57 | % Peak labels.
58 | h = Label.peak(S.Fit.Center(1, :), 'StringFormat', '%.1f', ...
59 | 'FontColor', [.3, .3, .3], 'LineWidth', 0, ...
60 | 'MinYPos', .1, 'MinYDist', .01, 'PlotLine', h);
61 |
62 | % Reconfigure the axes.
63 | extent = vertcat(h.Extent);
64 | yLim(2) = max(extent(:, 2) + extent(:, 4));
65 | yLim(2) = yLim(1) + diff(yLim) / (1 - TICK_LENGTH / AXES_SIZE(2));
66 | ax.YLim = yLim;
67 |
68 | % Reconfigure the layout.
69 | margin = ax.TightInset + .1;
70 | ax.Position = pos + [margin(1), margin(2), 0, 0];
71 | pos = pos + [0, 0, margin(1) + margin(3), margin(2) + margin(4)];
72 | set(fig, {'Position', 'PaperPosition', 'PaperSize'}, {pos, pos, pos(3:4)});
73 |
74 | % Saving.
75 | print(fig, 'Er_PL_in_YSO.png', '-dpng', sprintf('-r%d', RESOLUTION));
76 | close(fig);
77 |
--------------------------------------------------------------------------------
/@PeakFit/model.m:
--------------------------------------------------------------------------------
1 | function [yModel, yPeak, yBaseline] = model(obj, varargin)
2 | %% Fit Model
3 | % [yModel, yPeak, yBaseline] = obj.model() returns a set of fit models
4 | % evaluated at the data points.
5 | %
6 | % [yModel, yPeak, yBaseline] = obj.model(x) evaluates the fit models at x
7 | % instead.
8 | %
9 | % Outputs:
10 | % yModel: The reconstructed data points from the fit results.
11 | %
12 | % yPeak: A cell containing the resconstructed data points of each peak.
13 | %
14 | % yBaseline: The reconstructed baseline points.
15 | %
16 | % Requires package:
17 | % - MatCommon_v1.0.0+
18 | %
19 | % Tested on:
20 | % - MATLAB R2013b
21 | %
22 | % Copyright: Herianto Lim (https://heriantolim.com)
23 | % Licensing: GNU General Public License v3.0
24 | % First created: 04/04/2013
25 | % Last modified: 25/10/2016
26 |
27 | yModel = [];
28 | yPeak = [];
29 | yBaseline = [];
30 |
31 | numPeaks = obj.NumPeaks;
32 | center = obj.Center;
33 | height = obj.Height;
34 | width = obj.Width;
35 |
36 | if numPeaks == 0 || isempty(center) || isempty(height) || isempty(width)
37 | return
38 | end
39 |
40 | %% Parse Inputs
41 | if nargin == 1
42 | xModel = obj.XData;
43 | elseif nargin > 2
44 | error('PeakfFit:model:TooManyInput', ...
45 | 'At most one input argument can be taken.');
46 | elseif isrealvector(varargin{1})
47 | xModel = varargin{1};
48 | else
49 | error('PeakFit:model:InvalidInput', ...
50 | 'Input to the domains for the model must be a vector of real numbers.');
51 | end
52 |
53 | %% Construct Baseline
54 | baseline = obj.Baseline;
55 |
56 | if obj.BaselinePolyOrder < 0 || isempty(baseline)
57 | yBaseline = zeros(size(xModel));
58 | else
59 | yBaseline = polyval(baseline(1, :), xModel);
60 | end
61 |
62 | %% Construct Peak
63 | yPeak = cell(1, numPeaks);
64 |
65 | for i = 1:numPeaks
66 |
67 | switch obj.PeakShape(i)
68 | case 1
69 | yPeak{i} = PeakFit.fnlorentzian(xModel, ...
70 | center(1, i), height(1, i), width(1, i));
71 | case 2
72 | yPeak{i} = PeakFit.fngaussian(xModel, ...
73 | center(1, i), height(1, i), width(1, i));
74 | otherwise
75 | error('PeakFit:model:UnexpectedInput', ...
76 | 'The specified peak shape is not recognized.');
77 | end
78 |
79 | end
80 |
81 | %% Construct Model
82 | yModel = yBaseline;
83 |
84 | for i = 1:numPeaks
85 | yModel = yModel + yPeak{i};
86 | end
87 |
88 | end
89 |
--------------------------------------------------------------------------------
/Examples/VO2_Raman.m:
--------------------------------------------------------------------------------
1 | %% PeakFit Example #2: VO2 Raman
2 | %
3 | % Copyright: Herianto Lim (https://heriantolim.com)
4 | % Licensing: GNU General Public License v3.0
5 | % First created: 29/10/2018
6 | % Last modified: 29/10/2018
7 |
8 | % Add the required packages using MatVerCon.
9 | % addpackage('MatCommon','MatGraphics','PeakFit');
10 |
11 | % Clear workspace variables.
12 | clear;
13 |
14 | % Load data. If fails, adjust the file path supplied to the argument.
15 | S = load('VO2_Raman.mat');
16 |
17 | % Perform Lorentzian peak fitting.
18 | S.Fit = PeakFit(S.Data, 'Window', [100, 900], 'PeakShape', 'Lorentzian', ...
19 | 'CenterLow', [521, 145, 198, 224, 258, 304, 310, 336, 387, 394, 430, 503, 588, 615, 665, 827], ...
20 | 'CenterUp', [524, 151, 202, 228, 263, 306, 315, 342, 394, 402, 450, 506, 597, 625, 675, 837], ...
21 | 'WidthUp', [4, 14, 10, 8, 10, 10, 10, 10, 18, 20, 40, 20, 30, 40, 20, 30], ...
22 | 'BaselinePolyOrder', 1);
23 |
24 | %% Plotting
25 | % Settings.
26 | Groot.usedefault();
27 | Groot.usedefault('latex', 8, .6);
28 | RESOLUTION = 300;
29 | AXES_SIZE = [12, 4];
30 | TICK_LENGTH = .2;
31 | CLIP_RANGE = [500, 540];
32 |
33 | % Plot data.
34 | xData = S.Fit.XData;
35 | yData = S.Fit.YData;
36 | xLim = S.Fit.Window;
37 | ix = (xData >= xLim(1) & xData <= xLim(2)) ...
38 | & (xData < CLIP_RANGE(1) | xData > CLIP_RANGE(2));
39 | xModel = linspace(xLim(1), xLim(2), ceil(RESOLUTION / 2.54 * AXES_SIZE(1)));
40 | [yModel, yPeak, yBaseline] = S.Fit.model(xModel);
41 | yLim = [min(min(yData), min(yBaseline)), max(yData(ix)) / .6];
42 |
43 | % Figure.
44 | fig = docfigure(AXES_SIZE);
45 |
46 | % Axes.
47 | pos = [0, 0, AXES_SIZE];
48 | ax = axes('Position', pos, 'XLim', xLim, 'YLim', yLim, ...
49 | 'YTickLabel', '', 'XDir', 'reverse');
50 | xlabel('Raman shift (cm$^{-1}$)');
51 | ylabel('Intensity (arb. unit)');
52 | fixticklength(.2);
53 |
54 | % Plots.
55 | N = S.Fit.NumPeaks;
56 | h = plot(xData, yData, 'Color', 'b');
57 |
58 | for j = 1:N
59 | plot(xModel, yBaseline + yPeak{j}, 'Color', 'r', 'LineWidth', .3);
60 | end
61 |
62 | h(2) = plot(xModel, yModel, 'Color', 'g', 'LineWidth', .3);
63 |
64 | % Peak labels.
65 | h = Label.peak(S.Fit.Center(1, :), 'StringFormat', '%.1f', ...
66 | 'FormatSpec', [2, ones(1, N - 1)], ...
67 | 'FontColor', {[.3, .3, .3], [1, .5, 0]}, 'LineWidth', 0, ...
68 | 'MinYPos', .1, 'MinYDist', .01, 'PlotLine', h, 'ClipRange', CLIP_RANGE);
69 |
70 | % Reconfigure the axes.
71 | extent = vertcat(h.Extent);
72 | yLim(2) = max(extent(:, 2) + extent(:, 4));
73 | yLim(2) = yLim(1) + diff(yLim) / (1 - TICK_LENGTH / AXES_SIZE(2));
74 | ax.YLim = yLim;
75 |
76 | % Reconfigure the layout.
77 | margin = ax.TightInset + .1;
78 | ax.Position = pos + [margin(1), margin(2), 0, 0];
79 | pos = pos + [0, 0, margin(1) + margin(3), margin(2) + margin(4)];
80 | set(fig, {'Position', 'PaperPosition', 'PaperSize'}, {pos, pos, pos(3:4)});
81 |
82 | % Saving.
83 | print(fig, 'VO2_Raman.png', '-dpng', sprintf('-r%d', RESOLUTION));
84 | close(fig);
85 |
--------------------------------------------------------------------------------
/@PeakFit/transformpolycoeff.m:
--------------------------------------------------------------------------------
1 | function p = transformpolycoeff(p, varargin)
2 | %% Transform Polynomial Coefficient
3 | % This method transform a polynomial-coefficient vector p into another
4 | % polynomial-coefficient vector p' such that the corresponding polynomial
5 | % function y(x) transforms under: x -> x' = a x + b and y -> y' = c y + d.
6 | %
7 | % Syntax:
8 | % p = PeakFit.transformpolycoeff(p, a)
9 | % p = PeakFit.transformpolycoeff(p, a, b)
10 | % p = PeakFit.transformpolycoeff(p, a, b, c)
11 | % p = PeakFit.transformpolycoeff(p, a, b, c, d)
12 | %
13 | % Inputs
14 | % p: The polynomial coefficients in a row vector. It can be inputted as a
15 | % 3-row matrix, where the 1st, 2nd and 3rd row specifies the values of
16 | % p, the lower bound of p, and the upper bound of p respectively.
17 | %
18 | % a, b, c, d: The linear transformation coefficiens.
19 | %
20 | % Requires package:
21 | % - MatCommon_v1.0.0+
22 | %
23 | % Tested on:
24 | % - MATLAB R2013b
25 | % - MATLAB R2015b
26 | %
27 | % Copyright: Herianto Lim (https://heriantolim.com)
28 | % Licensing: GNU General Public License v3.0
29 | % First created: 27/10/2016
30 | % Last modified: 27/10/2016
31 |
32 | assert(iscomplexmatrix(p) && (isrow(p) || size(p, 1) == 3), ...
33 | 'PeakFit:transformpolycoeff:InvalidInput', ...
34 | 'Input to the polynomial-coefficient vector must be a row vector or a 3-row matrix of complex numbers.');
35 | assert(all(cellfun(@isrealscalar, varargin)), ...
36 | 'PeakFit:transformpolycoeff:InvalidInput', ...
37 | 'Input to the linear transformation coefficients must be a real scalar.');
38 |
39 | N = nargin;
40 |
41 | if N == 1
42 | return
43 | end
44 |
45 | [m, n] = size(p);
46 | a = varargin{1};
47 |
48 | if a == 0
49 | p = nan(m, n);
50 | return
51 | end
52 |
53 | if N > 2
54 | b = varargin{2};
55 | else
56 | b = 0;
57 | end
58 |
59 | if N > 3
60 | c = varargin{3};
61 |
62 | if c == 0
63 | p = zeros(m, n);
64 | return
65 | end
66 |
67 | else
68 | c = 1;
69 | end
70 |
71 | if N > 4
72 | d = varargin{4};
73 | else
74 | d = 0;
75 | end
76 |
77 | if n > 1
78 | % compute the upper triangular matrix of the combinatorials
79 | A = zeros(n);
80 | N = n - 1;
81 |
82 | for i = 0:N
83 |
84 | for j = 0:i
85 | A(n - i, n - i + j) = A(n - i, n - i + j) ...
86 | + nchoosek(i, j) * a^(-i) * (-b)^j;
87 | end
88 |
89 | end
90 |
91 | % transform the polynomial coefficients
92 | p(1, :) = p(1, :) * A;
93 |
94 | % transform the lower and upper bounds
95 | if m > 2
96 | p2 = zeros(1, n);
97 | p3 = zeros(1, n);
98 |
99 | for j = 1:n
100 |
101 | for i = 1:j
102 |
103 | if A(i, j) < 0
104 | p2(j) = p2(j) + p(3, j) * A(i, j);
105 | p3(j) = p3(j) + p(2, j) * A(i, j);
106 | else
107 | p2(j) = p2(j) + p(2, j) * A(i, j);
108 | p3(j) = p3(j) + p(3, j) * A(i, j);
109 | end
110 |
111 | end
112 |
113 | end
114 |
115 | p(2, :) = p2;
116 | p(3, :) = p3;
117 | end
118 |
119 | end
120 |
121 | p(:, n) = p(:, n) + d / c;
122 | p = p * c;
123 |
124 | if m > 2 && c < 0
125 | p([2, 3], :) = p([3, 2], :);
126 | end
127 |
128 | end
129 |
--------------------------------------------------------------------------------
/@PeakFit/findmaxima.m:
--------------------------------------------------------------------------------
1 | function [xm, ym] = findmaxima(obj, varargin)
2 | %% Find Maxima
3 | % [xm, ym] = obj.findmaxima() locates the maxima in the curve data stored
4 | % in the object and returns the coordinates of the maxima.
5 | %
6 | % [xm, ym] = obj.findmaxima(window) locates the maxima within the
7 | % specified x window. window is a real vector of length two.
8 | %
9 | % [xm, ym] = obj.findmaxima(n) locates exactly n maxima.
10 | %
11 | % [xm, ym] = obj.findmaxima(window, n) locates n maxima within the window.
12 | %
13 | % [xm, ym] = obj.findmaxima(x, y, ...) use the x and y vector as the data
14 | % points instead of the data stored in the object.
15 | %
16 | % The curve is smoothed first prior to finding the maxima with a simple
17 | % moving mean. The MovMeanWidth property is used as the sample
18 | % width of the moving mean.
19 | %
20 | % Requires package:
21 | % - MatCommon_v1.0.0+
22 | %
23 | % Tested on:
24 | % - MATLAB R2013b
25 | % - MATLAB R2015b
26 | %
27 | % Copyright: Herianto Lim (https://heriantolim.com)
28 | % Licensing: GNU General Public License v3.0
29 | % First created: 27/03/2013
30 | % Last modified: 05/11/2016
31 |
32 | %% Input Validation and Parsing
33 | N = nargin - 1;
34 |
35 | if N == 0
36 | x = obj.XData;
37 | y = obj.YData;
38 | n = 0;
39 | else
40 | k = N;
41 |
42 | if isintegerscalar(varargin{k}) && varargin{k} >= 0
43 | n = varargin{k};
44 | k = k - 1;
45 | else
46 | n = 0;
47 | end
48 |
49 | if k > 0 && isrealvector(varargin{k}) && numel(varargin{k}) == 2
50 | w = sort(varargin{k});
51 | k = k - 1;
52 | else
53 | w = [];
54 | end
55 |
56 | if k > 1 && isrealvector(varargin{k}) && isrealvector(varargin{k - 1}) ...
57 | && numel(varargin{k}) == numel(varargin{k - 1})
58 | y = varargin{k};
59 | x = varargin{k - 1};
60 | k = k - 2;
61 | else
62 | x = obj.XData;
63 | y = obj.YData;
64 | end
65 |
66 | if k > 0
67 | error('PeakFit:findmaxima:UnexpectedInput', ...
68 | 'One or more inputs are not recognized.');
69 | end
70 |
71 | end
72 |
73 | % Trim data points
74 | if ~isempty(w)
75 | ix = x >= w(1) & x <= w(2);
76 | x = x(ix);
77 | y = y(ix);
78 | end
79 |
80 | %% Finding the Maxima
81 | N = numel(x);
82 |
83 | if N == 0
84 | % No data, return empty
85 | xm = [];
86 | ym = [];
87 | elseif n == 1 || N < 4
88 | % The tallest point is always the maxima
89 | [ym, k] = max(y);
90 | xm = x(k);
91 | else
92 | % The gradient of the smoothed curve
93 | w = obj.MovMeanWidth;
94 |
95 | if w < 1
96 | w = ceil(w * N);
97 | end
98 |
99 | y1 = diff(movmean(y, w)) ./ diff(x);
100 |
101 | % Find all maxima and give each a rank according to the average of their
102 | % adjacent absolute gradients
103 | k = N - 2;
104 | ix = zeros(1, k);
105 | rank = zeros(1, k);
106 | m = 0;
107 |
108 | for i = 1:k
109 |
110 | if y1(i) > 0 && y1(i + 1) < 0
111 | m = m + 1;
112 | ix(m) = i + 1;
113 | rank(m) = mean(abs(y1(i:i + 1)));
114 | end
115 |
116 | end
117 |
118 | ix = ix(1:m);
119 | rank = rank(1:m);
120 |
121 | if m == 0
122 | % y is either monotonically increasing or decreasing
123 | [ym, k] = max(y);
124 | xm = x(k);
125 | else
126 |
127 | if n > 0
128 |
129 | if m > n
130 | [~, k] = sort(rank, 'descend');
131 | ix = ix(k);
132 | ix = sort(ix(1:n));
133 | elseif m < n
134 | warning('PeakFit:find:FoundFewerPeaks', ...
135 | 'Requested to find %d peaks, but only %d peaks are found.', ...
136 | n, m);
137 | end
138 |
139 | end
140 |
141 | xm = x(ix);
142 | ym = y(ix);
143 | end
144 |
145 | end
146 |
147 | end
148 |
--------------------------------------------------------------------------------
/@PeakFit/disp.m:
--------------------------------------------------------------------------------
1 | function disp(obj)
2 | %% Display Object Properties
3 | %
4 | % Copyright: Herianto Lim (https://heriantolim.com)
5 | % Licensing: GNU General Public License v3.0
6 | % First created: 08/04/2013
7 | % Last modified: 25/10/2016
8 |
9 | fprintf('\nFit Options:\n');
10 | fprintf('\t%18s: %s\n', 'Method', obj.Method);
11 | fprintf('\t%18s: %s\n', 'Robust', obj.Robust);
12 | fprintf('\t%18s: %s\n', 'Algorithm', obj.Algorithm);
13 | fprintf('\t%18s: %.2e\n', 'DiffMaxChange', obj.DiffMaxChange);
14 | fprintf('\t%18s: %.2e\n', 'DiffMinChange', obj.DiffMinChange);
15 | fprintf('\t%18s: %d\n', 'MaxFunEvals', obj.MaxFunEvals);
16 | fprintf('\t%18s: %d\n', 'MaxIters', obj.MaxIters);
17 | fprintf('\t%18s: %.2e\n', 'TolFun', obj.TolFun);
18 | fprintf('\t%18s: %.2e\n', 'TolX', obj.TolX);
19 |
20 | exitFlag = obj.ExitFlag;
21 |
22 | if ~isempty(exitFlag)
23 | numPeaks = obj.NumPeaks;
24 | header = ' Lower Bound Start Point Upper Bound Lower CI Convergence Upper CI RelUncert\n';
25 | lineFormat = ' %11.4e %11.4e %11.4e %11.4e %11.4e %11.4e %11.4e\n';
26 |
27 | fprintf('\nArea:\n\t Peak');
28 | fprintf(header);
29 | lower = obj.AreaLow;
30 | start = obj.AreaStart;
31 | upper = obj.AreaUp;
32 | x = obj.Area;
33 |
34 | for i = 1:numPeaks
35 | fprintf('\t%5d', i);
36 | fprintf(lineFormat, lower(i), start(i), upper(i), x(2, i), ...
37 | x(1, i), x(3, i), abs((x(3, i) - x(2, i)) / x(1, i)) / 2);
38 | end
39 |
40 | fprintf('\nCenter:\n\t Peak');
41 | fprintf(header);
42 | lower = obj.CenterLow;
43 | start = obj.CenterStart;
44 | upper = obj.CenterUp;
45 | x = obj.Center;
46 |
47 | for i = 1:numPeaks
48 | fprintf('\t%5d', i);
49 | fprintf(lineFormat, lower(i), start(i), upper(i), x(2, i), ...
50 | x(1, i), x(3, i), abs((x(3, i) - x(2, i)) / x(1, i)) / 2);
51 | end
52 |
53 | fprintf('\nHeight:\n\t Peak');
54 | fprintf(header);
55 | lower = obj.HeightLow;
56 | start = obj.HeightStart;
57 | upper = obj.HeightUp;
58 | x = obj.Height;
59 |
60 | for i = 1:numPeaks
61 | fprintf('\t%5d', i);
62 | fprintf(lineFormat, lower(i), start(i), upper(i), x(2, i), ...
63 | x(1, i), x(3, i), abs((x(3, i) - x(2, i)) / x(1, i)) / 2);
64 | end
65 |
66 | fprintf('\nWidth:\n\t Peak');
67 | fprintf(header);
68 | lower = obj.WidthLow;
69 | start = obj.WidthStart;
70 | upper = obj.WidthUp;
71 | x = obj.Width;
72 |
73 | for i = 1:numPeaks
74 | fprintf('\t%5d', i);
75 | fprintf(lineFormat, lower(i), start(i), upper(i), x(2, i), ...
76 | x(1, i), x(3, i), abs((x(3, i) - x(2, i)) / x(1, i)) / 2);
77 | end
78 |
79 | Q = obj.BaselinePolyOrder + 1;
80 |
81 | if Q > 0
82 | fprintf('\nBaseline:\n\tCoeff');
83 | fprintf(header);
84 | lower = obj.BaselineLow;
85 | start = obj.BaselineStart;
86 | upper = obj.BaselineUp;
87 | x = obj.Baseline;
88 |
89 | for i = 1:Q
90 | fprintf('\t%5s', sprintf('p%d', i));
91 | fprintf(lineFormat, lower(i), start(i), upper(i), x(2, i), ...
92 | x(1, i), x(3, i), abs((x(3, i) - x(2, i)) / x(1, i)) / 2);
93 | end
94 |
95 | end
96 |
97 | fprintf('\nGoodness of Fit:\n');
98 | fprintf('\t%18s: %.4g\n', 'RelStDev', obj.RelStDev);
99 | fprintf('\t%18s: %.4g\n', 'CoeffDeterm', obj.CoeffDeterm);
100 | fprintf('\t%18s: %.4g\n', 'AdjCoeffDeterm', obj.AdjCoeffDeterm);
101 |
102 | fprintf('\nIteration Report:\n');
103 | fprintf('\t%18s: %d\n', 'NumFunEvals', obj.NumFunEvals);
104 | fprintf('\t%18s: %d\n', 'NumIters', obj.NumIters);
105 |
106 | if exitFlag > 0
107 | exitStatus = 'converged';
108 | elseif exitFlag < 0
109 | exitStatus = 'diverged';
110 | elseif obj.NumFunEvals > obj.MaxFunEvals
111 | exitStatus = 'MaxFunEvals was exceeded';
112 | elseif obj.NumIters > obj.MaxIters
113 | exitStatus = 'MaxIters was exceeded';
114 | else
115 | exitStatus = 'fail';
116 | end
117 |
118 | fprintf('\t%18s: %d (%s)\n', 'ExitFlag', exitFlag, exitStatus);
119 | end
120 |
121 | end
122 |
--------------------------------------------------------------------------------
/@PeakFit/convertunit.m:
--------------------------------------------------------------------------------
1 | function obj = convertunit(obj, unitFrom, unitTo, varargin)
2 | %% Convert Units
3 | % This method converts the values of XData, Center, Baseline, and other
4 | % related properties in a PeakFit object according to a unit conversion.
5 | %
6 | % Available units to be converted from or to are:
7 | % 'eV' : electron volt
8 | % 'percm' : cm^{-1} (wavenumber)
9 | % 'Ramanshift': cm^{-1} (Raman shift)
10 | % When converting to or from Raman shift, an additional argument is
11 | % required that specifies the excitation wavelength in nanometer.
12 | %
13 | % Examples:
14 | % obj=convertunit(obj, 'nm', 'eV');
15 | % converts from nanometer to electron volt
16 | % obj=convertunit(obj, 'eV', 'Ramanshift', 532);
17 | % converts from electron volt to Raman shift at 532nm excitation.
18 | %
19 | % Requires package:
20 | % - MatCommon_v1.0.0+
21 | % - PhysConst_v1.0.0+
22 | %
23 | % Tested on:
24 | % - MATLAB R2013b
25 | % - MATLAB R2015b
26 | %
27 | % Copyright: Herianto Lim (https://heriantolim.com)
28 | % Licensing: GNU General Public License v3.0
29 | % First created: 27/10/2016
30 | % Last modified: 27/10/2016
31 |
32 | %% Constants
33 | DEF_UNITS = {'eV', 'percm', 'Ramanshift'};
34 |
35 | %% Input Validation and Parsing
36 | assert(isstringscalar(unitFrom) && isstringscalar(unitTo), ...
37 | 'PeakFit:convertunit:InvalidInput', ...
38 | 'Input to the units name must be a string scalar.');
39 |
40 | if strcmp(unitFrom, unitTo)
41 | return
42 | end
43 |
44 | assert(any(strcmp(unitFrom, DEF_UNITS)) && any(strcmp(unitTo, DEF_UNITS)), ...
45 | 'PeakFit:convertunit:UnexpectedCase', ...
46 | 'Conversion of the units from %s to %s has not been defined in the code.', ...
47 | unitFrom, unitTo);
48 |
49 | %% Conversion Coefficients
50 | ME1 = MException('PeakFit:convertunit:TooFewInput', ...
51 | 'Additional input arguments are required when converting from %s to %s.', ...
52 | unitFrom, unitTo);
53 | ME2 = MException('PeakFit:convertunit:InvalidInput', ...
54 | 'The additional input arguments failed validation.');
55 |
56 | switch unitFrom
57 | case 'eV'
58 |
59 | switch unitTo
60 | case 'percm'
61 | a = Constant.ElementaryCharge / Constant.Planck ...
62 | / Constant.LightSpeed / 100;
63 | b = 0;
64 | case 'Ramanshift'
65 | a = -Constant.ElementaryCharge / Constant.Planck ...
66 | / Constant.LightSpeed / 100;
67 |
68 | if nargin < 4
69 | throw(ME1);
70 | elseif ~isrealscalar(varargin{1}) && varargin{1} <= 0
71 | throw(ME2);
72 | end
73 |
74 | b = 1e7 / varargin{1};
75 | end
76 |
77 | case 'percm'
78 |
79 | switch unitTo
80 | case 'eV'
81 | a = 1e2 * Constant.Planck * Constant.LightSpeed ...
82 | / Constant.ElementaryCharge;
83 | b = 0;
84 | case 'Ramanshift'
85 | a = -1;
86 |
87 | if nargin < 4
88 | throw(ME1);
89 | elseif ~isrealscalar(varargin{1}) && varargin{1} <= 0
90 | throw(ME2);
91 | end
92 |
93 | b = 1e7 / varargin{1};
94 | end
95 |
96 | case 'Ramanshift'
97 |
98 | if nargin < 4
99 | throw(ME1);
100 | elseif ~isrealscalar(varargin{1}) && varargin{1} <= 0
101 | throw(ME2);
102 | end
103 |
104 | switch unitTo
105 | case 'eV'
106 | a = -1e2 * Constant.Planck * Constant.LightSpeed ...
107 | / Constant.ElementaryCharge;
108 | b = -a * 1e7 / varargin{1};
109 | case 'percm'
110 | a = -1;
111 | b = 1e7 / varargin{1};
112 | end
113 |
114 | end
115 |
116 | %% Change the Object Properties
117 | obj.XData = a * obj.XData + b;
118 | obj.Window = a * obj.Window + b;
119 |
120 | obj.CenterStart = a * obj.CenterStart + b;
121 |
122 | if a < 0
123 | obj.Center = a * obj.Center([1, 3, 2], :) + b;
124 | obj.CenterLow = a * obj.CenterUp + b;
125 | obj.CenterUp = a * obj.CenterLow + b;
126 | else
127 | obj.Center = a * obj.Center + b;
128 | obj.CenterLow = a * obj.CenterLow + b;
129 | obj.CenterUp = a * obj.CenterUp + b;
130 | end
131 |
132 | if obj.BaselinePolyOrder >= 0
133 | obj.Baseline = PeakFit.transformpolycoeff(obj.Baseline, a, b);
134 | B = [obj.BaselineStart; obj.BaselineLow; obj.BaselineUp];
135 | B = PeakFit.transformpolycoeff(B, a, b);
136 | obj.BaselineStart = B(1, :);
137 | obj.BaselineLow = B(2, :);
138 | obj.BaselineUp = B(3, :);
139 | end
140 |
141 | a = abs(a);
142 | obj.Width = a * obj.Width;
143 | obj.WidthStart = a * obj.WidthStart;
144 | obj.WidthLow = a * obj.WidthLow;
145 | obj.WidthUp = a * obj.WidthUp;
146 | obj.AreaStart = a * obj.AreaStart;
147 | obj.AreaLow = a * obj.AreaLow;
148 | obj.AreaUp = a * obj.AreaUp;
149 |
150 | end
151 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PeakFit
2 | **PeakFit** provides a tool to fit spectral data with a linear combination of symmetric peak functions such as Gaussian or Lorentzian. The background component of the spectra can be optionally taken into account by specifying the related parameter. In which case, the algorithm will attempt to fit the background with a polynomial function of the given order.
3 |
4 | The fit model is given by:
5 |
6 | f(*x*) ~ peak1(*x*) + peak2(*x*) + ... + peakN(*x*) + polynomial(*x*)
7 |
8 | Each peak function is characterized by three fit coefficients: `Center`, `Width`, and either one of `Area` and `Height`. The polynomial function is characterized by n+1 fit coefficients, where n is the order of the polynomial.
9 |
10 | ## Licensing
11 | This software is licensed under the GNU General Public License (version 3).
12 |
13 | ## Tested On
14 | - MATLAB R2013b - R2018a
15 |
16 | ## Requirements
17 | - MATLAB Curve Fitting Toolbox
18 | - [MatCommon](https://github.com/heriantolim/MatCommon)
19 | - [MatGraphics](https://github.com/heriantolim/MatGraphics) - required for doing the examples
20 | - [PhysConst](https://github.com/heriantolim/PhysConst) - required for the `convertunit` method
21 |
22 | ## Setting Up
23 | 1. Download or git-clone this repository and other repositories listed in the [Requirements](https://github.com/heriantolim/PeakFit#requirements).
24 | 2. Add the repositories to the MATLAB's search path via `addpath(genpath( ... ))` OR this [version control system](https://github.com/heriantolim/MatlabVerCon).
25 |
26 | ## Usage
27 | Construct the PeakFit object in the following ways, and the fit results will be populated in the object's [public properties](https://github.com/heriantolim/PeakFit#public-properties).
28 |
29 | ```MATLAB
30 | obj = PeakFit(Data, ... Name-Value ...)
31 | ```
32 |
33 | OR
34 |
35 | ```MATLAB
36 | obj = PeakFit(XData, YData, ... Name-Value ...)
37 | ```
38 |
39 | OR
40 |
41 | ```MATLAB
42 | % Create an empty PeakFit object.
43 | obj = PeakFit();
44 |
45 | % Specify the data points and peak-fit settings via property assignments.
46 | obj.XData = ... ;
47 | obj.YData = ... ;
48 | obj.Property1Name = Value1;
49 | obj.Property2Name = Value2;
50 | ...
51 |
52 | % Perform the peak fitting by reinstantiating the PeakFit object.
53 | obj = PeakFit(obj);
54 | ```
55 |
56 | `Data` must be specified as a two-column (or two-row) matrix where the first column (or first row) is the X data points and the second column (or second row) is the Y data points. In the alternative syntax, `XData` and `YData` are respectively the X and the Y data points, specified as vectors, of the curve to be fitted.
57 |
58 | The peak-fit settings can be specified after the mandatory arguments in Name-Value syntax, e.g. `PeakFit(Data, 'Window', [100,900], 'NumPeaks', 3)`. If no settings are specified, the algorithm will attempt to fit all peaks in the data using the default settings. The default behavior may not be optimal for noisy data. See [Best Practices](https://github.com/heriantolim/PeakFit#best-practices) for recommendations in making an optimal fit.
59 |
60 | ### Name-Value Pair Arguments
61 | Any of the [public properties](https://github.com/heriantolim/PeakFit#public-properties) can be specified as arguments in Name-Value syntax during the object construction. Specifying other things as Name-Value arguments will return an error.
62 |
63 | ## Examples
64 | ### Default Behavior
65 | If the `PeakFit` is called without specifying the number of peaks, start points, or lower or upper bounds, then the algorithm will attempt to fit all peaks that it can guess. The following image is a photoluminescence spectrum of Er3+ in Y2SiO5 at near-liquid N2 temperature. The spectrum was fitted using the command:
66 | ```MATLAB
67 | Fit = PeakFit(Data, 'PeakShape', 'Lorentzian');
68 | ```
69 | The full code is given in [Examples/Er_PL_in_YSO.m](/Examples/Er_PL_in_YSO.m). It can be seen that many of the peaks were not resolved properly, and only the tallest peaks were correctly identified.
70 |
71 | 
72 |
73 | ### Best Practices
74 | The PeakFit algorithm works best if the lower and upper bound of the peak `Center`, the upper bound of the peak `Width`, and the baseline polynomial order are specified, as done in the following example. The following Raman spectrum of VO2, taken at near-liquid N2 temperature ([Lim2014](https://doi.org/10.1063/1.4867481)), was fitted using the command:
75 | ```MATLAB
76 | Fit = PeakFit(Data, 'PeakShape', 'Lorentzian', ...
77 | 'CenterLow', [...], ...
78 | 'CenterUp', [...], ...
79 | 'WidthUp', [...], ...
80 | 'BaselinePolyOrder', n);
81 | ```
82 | The full code is given in [Examples/VO2_Raman.m](/Examples/VO2_Raman.m). Constructing the constraints for the fitting often require guess work, but the constraints do not have to be narrow to get a good accuracy. In some cases, the approximate locations of the peaks are known in the literature, and the fit constraints can be defined from this knowledge.
83 |
84 | 
85 |
86 | ## Public Properties
87 | - `Data`, `XData`, `YData`: The data points of the curve to be fitted. Please ensure that the Y data points are all positive, otherwise the peak fitting may not work properly.
88 | - `Window`: A vector of length two [*a*, *b*] that limits the fitting to only the data points whose X coordinates lies within [*a*, *b*].
89 | - `NumPeaks`: The number of peaks wished to be fitted. When the fitting peak shapes, start points, lower, or upper bounds are set with vectors of length greater than `NumPeaks`, then `NumPeaks` will be incremented to adjust to the maximum length of these vectors. When the maximum length of these vectors is less, then these vectors will be expanded and filled with the default values. When `NumPeaks`=0 and all the start point, lower, and upper are not set, then the algorithm will attempt to fit all peaks that it can guess in the curve. Defaults to 0.
90 | - `PeakShape`: A string vector that specifies the peak shape of each peak. The choices of `PeakShape` currently are: 'Lorentzian' (1) and 'Gaussian' (2). `PeakShape` may be set with an integer, the initial of these names, e.g. 'L' or 'G', or the full name, e.g. 'Lorentzian'. When the length of `PeakShape` is less than `NumPeaks`, the remaining peaks will be set with the default `PeakShape`, which is 'Lorentzian'. If PeakShape contains only one element, then the default value is the same as that element.
91 | - `BaselinePolyOrder`: An integer that specifies the order of the polynomial function used to fit the background of the spectrum. Defaults to 0, which means a constant polynomial. Set this to a negative value to exclude the polynomial from the fit model.
92 |
93 | ### Fit Results
94 | - (Read-only) `Peak`: A struct containing the fit results for each peak.
95 | - (Read-only) `Base`: A struct containing the fit results for the baseline.
96 | - (Read-only) `Area`, `Center`, `Height`, `Width`: A 3-by-`NumPeaks` matrix that stores the fit results for the area, center, height, and width, respectively; with each column correspond to the fit results for a particular peak. The first row holds the values at convergence, and the second (third) row holds the 95% CI lower (upper) bounds. Note that `Area` (or `Height`) is a redundant variable to the fit model, as it can be computed from `Width` and `Height` (or `Area`). Hence, it would be enough to specify the start points, lower or upper bounds for the `Area` or `Height` alone, as one can be computed from the other for any given `Width`.
97 | - (Read-only) `Baseline`: A 3-by-(n+1) matrix, where n=`BaselinePolyOrder`, that stores the fit results for the baseline. The elements in the i-th column correspond to the fit results for the x^(n-i+1) polynomial coefficient. The first row holds the values at convergence, and the second (third) row holds the 95% CI lower (upper) bounds.
98 | - (Read-only) `RelStDev`: The relative standard deviation of the fit results.
99 | - (Read-only) `CoeffDeterm`: The coefficient of determination of the fit results.
100 | - (Read-only) `AdjCoeffDeterm`: The degree-of-freedom adjusted coefficient of determination of the fit results.
101 | - (Read-only) `NumFunEvals`: The number of function evaluations.
102 | - (Read-only) `NumIters`: The number of iterations.
103 | - (Read-only) `ExitFlag`: The exit condition of the algorithm. Positive flags indicate convergence, within tolerances. Zero flags indicate that the maximum number of function evaluations or iterations was exceeded. Negative flags indicate that the algorithm did not converge to a solution.
104 |
105 | ### Fitting Start Points
106 | - `AreaStart`, `CenterStart`, `WidthStart`, `HeightStart`, `BaselineStart`: A vector of initial values for the area, center, width, height, and baseline coefficients, respectively. The default values are determined heuristically. To make certain properties default, set their values to NaN. They will be then replaced with the default values upon fitting.
107 |
108 | ### Fitting Lower Bounds
109 | - `AreaLow`, `CenterLow`, `WidthLow`, `HeightLow`, `BaselineLow`: A vector of lower bounds for the area, center, width, height, and baseline coefficients, respectively. The default values are determined heuristically. To make certain properties default, set their values to -Inf. They will be then replaced with the default values upon fitting.
110 |
111 | ### Fitting Upper Bounds
112 | - `AreaUp`, `CenterUp`, `WidthUp`, `HeightUp`, `BaselineUp`: A vector of upper bounds for the area, center, width, height, and baseline coefficients, respectively. The default values are determined heuristically. To make certain properties default, set their values to Inf. They will be then replaced with the default values upon fitting.
113 |
114 | ### Algorithm Parameters
115 | - (Read-only) `Method`='NonLinearLeastSquares'; The method used for the fitting.
116 | - `Robust`: The type of the least-squares method to be used in the fitting. Avaliable values are 'off', 'LAR' (least absolute residual method), and 'Bisquare' (bisquare weight method). Defaults to 'off'.
117 | - `Algorithm`: The algorithm to be used in the fitting. Available values are 'Lavenberg-Marquardt', 'Gauss-Newton', or 'Trust-Region'. Defaults to 'Trust-Region'.
118 | - `MovMeanWidth`: The window width of the moving average used for smoothing the curve in order to filter out the noise before finding the maximas. This parameter is used only when CenterStart is not given. The value of this can be set as a positive integer which specifies the width in terms of the number of data points, OR a real scalar between 0 and 1 which specifies the width as a fraction of the total number of data points. Defaults to 0.02.
119 | - `DiffMaxChange`: The maximum change in coefficients for finite difference gradients. Defaults to 0.1.
120 | - `DiffMinChange`: The minimum change in coefficients for finite difference gradients. Defaults to 1e-8.
121 | - `MaxFunEvals`: The allowed maximum number of evaluations of the model. Defaults to 1e5.
122 | - `MaxIters`: The maximum number of iterations allowed for the fit. Defaults to 1e3.
123 | - `TolFun`: The termination tolerance on the model value. Defaults to 1e-6.
124 | - `TolX`: The termination tolerance on the coefficient values. Defaults to 1e-6.
125 |
126 | ## Public Methods
127 | - `disp`: Displays the options, results, error and performance of the fitting.
128 | - `model`: Returns the reconstructed data points (model) using the fit results. See [@PeakFit/model.m](/@PeakFit/model.m) for more info.
129 | - `convertunit`: Converts the units of the data points and the fit results. Available units to be converted from or to are: 'eV' (electron volt), 'percm'(wavenumber in cm^-1), 'Ramanshift' (Raman shift in cm^-1). When converting to or from Raman shift, an additional argument is required that specifies the excitation wavelength in nanometer. See [@PeakFit/convertunit.m](/@PeakFit/convertunit.m) for more info.
130 |
131 | ### Static Methods
132 | - `fnlorentzian`: The Lorentzian function. See [@PeakFit/fnlorentzian.m](/@PeakFit/fnlorentzian.m) for more info.
133 | - `fngaussian`: The Gaussian function. See [@PeakFit/fngaussian.m](/@PeakFit/fngaussian.m) for more info.
134 |
135 | ## See Also
136 | - [BiErfFit](https://github.com/heriantolim/BiErfFit)
137 |
--------------------------------------------------------------------------------
/@PeakFit/fit.m:
--------------------------------------------------------------------------------
1 | function obj = fit(obj)
2 | %% Peak Fitting
3 | % This method performs a curve fitting to a spectral data with a linear
4 | % combination of peak functions using the MATLAB Curve Fitting toolbox.
5 | %
6 | % The fit results and statistics will be stored in the object properties
7 | % after a successful calling of this method.
8 | %
9 | % The object properties related to the start points and constraints for
10 | % the fit parameters will also be initialized.
11 | %
12 | % This algorithm is far from perfect. A lot of things need fixing to adapt
13 | % to different scenarios or be more efficient.
14 | %
15 | % Tested on:
16 | % - MATLAB R2013b
17 | % - MATLAB R2015b
18 | %
19 | % Copyright: Herianto Lim (https://heriantolim.com)
20 | % Licensing: GNU General Public License v3.0
21 | % First created: 15/03/2013
22 | % Last modified: 30/12/2020
23 |
24 | x = obj.XData;
25 | y = obj.YData;
26 |
27 | if isempty(x) || isempty(y)
28 | return
29 | end
30 |
31 | %% Defaults
32 | HEIGHT_START = .85;
33 | HEIGHT_UP = 1.35;
34 | WIDTH_START = .5;
35 | WIDTH_UP = 1;
36 |
37 | %% Initialize the Fit Data
38 | assert(numel(x) == numel(y), ...
39 | 'PeakFit:fit:InconsistentNumPoints', ...
40 | 'The number of X and Y data points must be equal.');
41 |
42 | % Sort the points (x,y) in ascending order
43 | [x, ix] = sort(x);
44 | y = y(ix);
45 |
46 | % Update the object data
47 | obj.XData = x;
48 | obj.YData = y;
49 |
50 | % Trim data points
51 | if ~isempty(obj.Window)
52 | ix = x >= obj.Window(1) & x <= obj.Window(2);
53 | assert(sum(ix) >= obj.MinNumPoints, ...
54 | 'PeakFit:fit:InsufficientNumPoints', ...
55 | 'The number of data points within the fit window must be at least %d.', ...
56 | obj.MinNumPoints);
57 | x = x(ix);
58 | y = y(ix);
59 | else
60 | obj.Window = [x(1), x(end)];
61 | end
62 |
63 | % Perform linear mapping from [x(1),x(end)]->[0,1] and [min(y),max(y)]->[0,1]
64 | bp = obj.BaselinePolyOrder + 1;
65 | a = min(y);
66 | b = max(y);
67 |
68 | if bp < 1 && a > 0
69 | a = 0;
70 | end
71 |
72 | c = 1 / (b - a);
73 | d = -c * a;
74 | a = 1 / (x(end) - x(1));
75 | b = -a * x(1);
76 | x = a * x + b;
77 | y = c * y + d;
78 |
79 | %% Initialize the Fit Parameters
80 | % Find the number of peaks
81 | n = [numel(obj.CenterStart), numel(obj.CenterLow), numel(obj.CenterUp), ...
82 | numel(obj.HeightStart), numel(obj.HeightLow), numel(obj.HeightUp), ...
83 | numel(obj.WidthStart), numel(obj.WidthLow), numel(obj.WidthUp), ...
84 | numel(obj.AreaStart), numel(obj.AreaLow), numel(obj.AreaUp), ...
85 | obj.NumPeaks];
86 | np = numel(obj.PeakShape);
87 |
88 | if np > 1
89 | np = max(max(n), np);
90 | else
91 |
92 | if np == 0
93 | obj.PeakShape = obj.DefaultPeakShape;
94 | end
95 |
96 | np = max(n);
97 | end
98 |
99 | % Initialize the constraint and peak shape arrays
100 | if np == 0
101 | % Find all possible maxima
102 | [xm, ym] = obj.findmaxima(x, y);
103 | np = numel(xm);
104 | center = [xm; nan(2, np)];
105 | height = [HEIGHT_START * ym; nan(2, np)];
106 | width = nan(3, np);
107 | area = nan(3, np);
108 | ps = repmat(obj.PeakShape, 1, np);
109 | else
110 | % Fill the blank constraints with NaN
111 | n = np - n;
112 | center = [a * obj.CenterStart + b, nan(1, n(1));
113 | a * obj.CenterLow + b, nan(1, n(2));
114 | a * obj.CenterUp + b, nan(1, n(3))];
115 | height = [c * obj.HeightStart, nan(1, n(4));
116 | c * obj.HeightLow, nan(1, n(5));
117 | c * obj.HeightUp, nan(1, n(6))];
118 | width = [a * obj.WidthStart, nan(1, n(7));
119 | a * obj.WidthLow, nan(1, n(8));
120 | a * obj.WidthUp, nan(1, n(9))];
121 | area = [a * c * obj.AreaStart, nan(1, n(10));
122 | a * c * obj.AreaLow, nan(1, n(11));
123 | a * c * obj.AreaUp, nan(1, n(12))];
124 |
125 | if n(13) == 0
126 | ps = repmat(obj.PeakShape, 1, np);
127 | else
128 | ps = [obj.PeakShape, repmat(obj.DefaultPeakShape, 1, n(13))];
129 | end
130 |
131 | % If lower bounds exceed upper bounds, swap them
132 | for j = 1:np
133 |
134 | if center(2, j) > center(3, j)
135 | center([2, 3], j) = center([3, 2], j);
136 | end
137 |
138 | if height(2, j) > height(3, j)
139 | height([2, 3], j) = height([3, 2], j);
140 | end
141 |
142 | if width(2, j) > width(3, j)
143 | width([2, 3], j) = width([3, 2], j);
144 | end
145 |
146 | if area(2, j) > area(3, j)
147 | area([2, 3], j) = area([3, 2], j);
148 | end
149 |
150 | end
151 |
152 | end
153 |
154 | % If center starts are known, fill the blank height starts
155 | for j = 1:np
156 |
157 | if isfinite(center(1, j)) &&~isfinite(height(1, j))
158 | height(1, j) = HEIGHT_START * interp1(x, y, center(1, j));
159 | end
160 |
161 | end
162 |
163 | % If the lower and/or upper bounds exist, fill the blank start points
164 | for j = 1:np
165 |
166 | if all(isfinite(center(:, j)) == [0; 1; 1])
167 | [center(1, j), ym] = obj.findmaxima(x, y, center(2:3, j), 1);
168 |
169 | if ~isfinite(height(1, j))
170 | height(1, j) = HEIGHT_START * ym;
171 | end
172 |
173 | end
174 |
175 | if ~isfinite(height(1, j))
176 |
177 | if isfinite(height(3, j))
178 |
179 | if isfinite(height(2, j))
180 | height(1, j) = height(2, j) ...
181 | + HEIGHT_START * (height(3, j) - height(2, j));
182 | else
183 | height(1, j) = HEIGHT_START * height(3, j);
184 | end
185 |
186 | end
187 |
188 | end
189 |
190 | if ~isfinite(width(1, j))
191 |
192 | if isfinite(width(3, j))
193 |
194 | if isfinite(width(2, j))
195 | width(1, j) = width(2, j) ...
196 | + WIDTH_START * (width(3, j) - width(2, j));
197 | else
198 | width(1, j) = WIDTH_START * width(3, j);
199 | end
200 |
201 | end
202 |
203 | end
204 |
205 | if ~isfinite(area(1, j))
206 |
207 | if isfinite(area(3, j))
208 |
209 | if isfinite(area(2, j))
210 | area(1, j) = area(2, j) ...
211 | + HEIGHT_START * WIDTH_START * (area(3, j) - area(2, j));
212 | else
213 | area(1, j) = HEIGHT_START * WIDTH_START * area(3, j);
214 | end
215 |
216 | end
217 |
218 | end
219 |
220 | end
221 |
222 | % Fill the remaining blank center starts.
223 | % This block needs revision because center starts may not be initially ordered.
224 | ix = ~isfinite(center(1, :));
225 |
226 | if any(ix)
227 | ix = find(ix);
228 | w = diff(ix);
229 | s = ix([2, w] > 1);
230 | t = ix([w, 2] > 1);
231 | n = numel(s);
232 | w = zeros(n, 2);
233 |
234 | if s(1) > 1
235 | w(1, 1) = center(1, s(1) - 1) + obj.TolX;
236 | else
237 | w(1, 1) = x(1) - obj.TolX;
238 | end
239 |
240 | if t(n) < np
241 | w(n, 2) = center(1, t(n) + 1) - obj.TolX;
242 | else
243 | w(n, 2) = x(end) + obj.TolX;
244 | end
245 |
246 | for i = 2:n
247 | w(i, 1) = center(1, s(i) - 1) + obj.TolX;
248 | w(i - 1, 2) = center(1, t(i - 1) + 1) - obj.TolX;
249 | end
250 |
251 | for i = 1:n
252 | [xm, ym] = obj.findmaxima(x, y, w(i, :), t(i) - s(i) + 1);
253 | center(1, s(i):t(i)) = xm;
254 |
255 | for j = s(i):t(i)
256 |
257 | if ~isfinite(height(1, j)) ...
258 | &&~(isfinite(area(1, j)) && isfinite(width(1, j)))
259 | height(1, j) = HEIGHT_START * ym(j - s(i) + 1);
260 | end
261 |
262 | end
263 |
264 | end
265 |
266 | end
267 |
268 | % Compute the width or height constraints from the area constraints
269 | n = [1, 3, 2];
270 |
271 | for i = 1:3
272 |
273 | for j = 1:np
274 |
275 | if isfinite(area(i, j))
276 |
277 | if ~isfinite(width(i, j)) && isfinite(height(n(i), j))
278 | width(i, j) = PeakFit.computewidth(ps(j), ...
279 | area(i, j), height(n(i), j));
280 | elseif ~isfinite(height(i, j)) && isfinite(width(n(i), j))
281 |
282 | if area(i, j) < 0
283 | height(i, j) = PeakFit.computeheight(ps(j), ...
284 | area(n(i), j), width(i, j));
285 | else
286 | height(i, j) = PeakFit.computeheight(ps(j), ...
287 | area(i, j), width(n(i), j));
288 | end
289 |
290 | end
291 |
292 | end
293 |
294 | end
295 |
296 | end
297 |
298 | % Replace the blank width constraints with defaults
299 | width(3, ~isfinite(width(3, :))) = WIDTH_UP / sqrt(np);
300 | width(2, ~isfinite(width(2, :))) = 2 * mean(diff(x));
301 | ix = ~isfinite(width(1, :));
302 | width(1, ix) = max(width(2, ix), WIDTH_START * width(3, ix));
303 |
304 | % Replace the blank center constraints with defaults
305 | ix = ~isfinite(center(1, :));
306 | center(1, ix) = rand(1, sum(ix));
307 | ix = ~isfinite(center(2, :));
308 | center(2, ix) = center(1, ix) - width(1, ix);
309 | ix = ~isfinite(center(3, :));
310 | center(3, ix) = center(1, ix) + width(1, ix);
311 |
312 | % Replace the blank height constraints with defaults
313 | ix = ~isfinite(height(1, :));
314 | height(1, ix) = rand(1, sum(ix));
315 | w = 2 * obj.TolFun;
316 |
317 | for j = 1:np
318 |
319 | if height(1, j) < 0
320 |
321 | if ~isfinite(height(2, j))
322 | height(2, j) = -HEIGHT_UP ...
323 | * min(y(x >= center(2, j) & x <= center(3, j)));
324 | end
325 |
326 | if ~isfinite(height(3, j))
327 | height(3, j) = -w;
328 | end
329 |
330 | else
331 |
332 | if ~isfinite(height(2, j))
333 | height(2, j) = w;
334 | end
335 |
336 | if ~isfinite(height(3, j))
337 | height(3, j) = HEIGHT_UP ...
338 | * max(y(x >= center(2, j) & x <= center(3, j)));
339 | end
340 |
341 | end
342 |
343 | end
344 |
345 | % Compute the area from the height and width
346 | for i = 1:3
347 |
348 | for j = 1:np
349 |
350 | if ~isfinite(area(i, j))
351 | area(i, j) = PeakFit.computearea(ps(j), ...
352 | height(i, j), width(i, j));
353 | end
354 |
355 | end
356 |
357 | end
358 |
359 | % Set the baseline constraints
360 | if bp > 0
361 | % Set the y-axis intersect as the start point for the baseline
362 | baseline = zeros(1, bp);
363 | w = obj.MovMeanWidth;
364 |
365 | if w >= 1
366 | w = w / numel(x);
367 | end
368 |
369 | baseline(bp) = mean(y(x <= w / 2));
370 |
371 | % Use a fibonacci sequence to define the lower and upper bounds
372 | n = bp + 1;
373 | w = ones(1, n);
374 |
375 | for i = 3:n
376 | w(i) = w(i - 1) + w(i - 2);
377 | end
378 |
379 | w = flip(w);
380 | w(n) = [];
381 | baseline = [baseline; baseline - w; baseline + w];
382 | else
383 | baseline = zeros(3, 0);
384 | end
385 |
386 | %% Construct the Fit Coefficients and Expression
387 | coeff = cell(1, 3 * np);
388 |
389 | for i = 1:np
390 | coeff{i} = sprintf('c%d', i);
391 | coeff{np + i} = sprintf('h%d', i);
392 | coeff{2 * np + i} = sprintf('w%d', i);
393 | end
394 |
395 | if bp > 0
396 | coeff = [coeff, cell(1, bp)];
397 |
398 | for i = 1:bp
399 | coeff{3 * np + i} = sprintf('p%d', i);
400 | end
401 |
402 | end
403 |
404 | expr = cell(1, np);
405 |
406 | for i = 1:np
407 |
408 | switch ps(i)
409 | case 1
410 | expr{i} = sprintf('h%1$d*(w%1$d/2)^2/((x-c%1$d).^2+(w%1$d/2)^2)', i);
411 | case 2
412 | expr{i} = sprintf('h%1$d*exp(-4*log(2)*(x-c%1$d).^2/w%1$d^2)', i);
413 | otherwise
414 | error('PeakFit:fit:UnexpectedCase', ...
415 | 'Something went wrong. Please review the code.');
416 | end
417 |
418 | end
419 |
420 | expr = strjoin(expr, '+');
421 |
422 | if bp > 0
423 | n = bp - 2;
424 |
425 | for i = 1:n
426 | expr = [expr, sprintf('+p%d*x.^%d', i, bp - i)]; %#ok
427 | end
428 |
429 | if bp > 1
430 | expr = [expr, sprintf('+p%d*x', bp - 1)];
431 | end
432 |
433 | expr = [expr, sprintf('+p%d', bp)];
434 | end
435 |
436 | %% MATLAB Curve Fitting ToolBox
437 | FitOption = fitoptions('Method', obj.Method, ...
438 | 'Robust', obj.Robust, ...
439 | 'StartPoint', [center(1, :), height(1, :), width(1, :), baseline(1, :)], ...
440 | 'Lower', [center(2, :), height(2, :), width(2, :), baseline(2, :)], ...
441 | 'Upper', [center(3, :), height(3, :), width(3, :), baseline(3, :)], ...
442 | 'Algorithm', obj.Algorithm, ...
443 | 'DiffMaxChange', obj.DiffMaxChange, ...
444 | 'DiffMinChange', obj.DiffMinChange, ...
445 | 'MaxFunEvals', obj.MaxFunEvals, ...
446 | 'MaxIter', obj.MaxIters, ...
447 | 'TolFun', obj.TolFun, ...
448 | 'TolX', obj.TolX, ...
449 | 'Display', 'off');
450 | FitType = fittype(expr, ...
451 | 'coefficients', coeff, ...
452 | 'options', FitOption);
453 | warning('off', 'all');
454 | [FitObj, gof, FitOutput] = fit(x', y', FitType);
455 | warning('on', 'all');
456 | fitResult = [coeffvalues(FitObj); confint(FitObj)];
457 |
458 | %% Update Object Properties
459 | % Update the shape and number of peaks
460 | obj.NumPeaks = np;
461 | obj.PeakShape = ps;
462 |
463 | % Reverse mapping coefficients
464 | a = 1 / a;
465 | b = -a * b;
466 | c = 1 / c;
467 | d = -c * d;
468 |
469 | % Update the center, height, and width, after a reverse mapping
470 | center = a * center + b;
471 | height = c * height;
472 | width = a * width;
473 | area = a * c * area;
474 | obj.Center = a * fitResult(:, 1:np) + b;
475 | obj.Height = c * fitResult(:, np + 1:2 * np);
476 | obj.Width = a * fitResult(:, 2 * np + 1:3 * np);
477 | obj.CenterStart = center(1, :);
478 | obj.CenterLow = center(2, :);
479 | obj.CenterUp = center(3, :);
480 | obj.HeightStart = height(1, :);
481 | obj.HeightLow = height(2, :);
482 | obj.HeightUp = height(3, :);
483 | obj.WidthStart = width(1, :);
484 | obj.WidthLow = width(2, :);
485 | obj.WidthUp = width(3, :);
486 | obj.AreaStart = area(1, :);
487 | obj.AreaLow = area(2, :);
488 | obj.AreaUp = area(3, :);
489 |
490 | % Update the baseline, after a reverse mapping
491 | if bp > 0
492 | baseline = PeakFit.transformpolycoeff(baseline, a, b, c, d);
493 | obj.Baseline = PeakFit.transformpolycoeff(fitResult(:, 3 * np + 1:3 * np + bp), a, b, c, d);
494 | obj.BaselineStart = baseline(1, :);
495 | obj.BaselineLow = baseline(2, :);
496 | obj.BaselineUp = baseline(3, :);
497 | end
498 |
499 | % Update the goodness of fit
500 | obj.RelStDev = gof.rmse; % due to the transformation to [0,1],
501 | % the rmse is effectively a relative standard deviation
502 | obj.CoeffDeterm = gof.rsquare;
503 | obj.AdjCoeffDeterm = gof.adjrsquare;
504 |
505 | % Update the performance stats of the fitting
506 | obj.NumFunEvals = FitOutput.funcCount;
507 | obj.NumIters = FitOutput.iterations;
508 | obj.ExitFlag = FitOutput.exitflag;
509 |
510 | end
511 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/@PeakFit/PeakFit.m:
--------------------------------------------------------------------------------
1 | classdef PeakFit
2 | %% PeakFit Class
3 | % Fit a spectral curve with a linear combination of symmetric peak
4 | % functions such as Gaussian, Lorentzian, etc. A baseline polynomial
5 | % function may be included to represent a 'background' contribution to the
6 | % spectra.
7 | %
8 | % Constructions:
9 | % A PeakFit object can be constructed in two ways.
10 | %
11 | % The first is by creating an empty PeakFit object and specifying the
12 | % fitting parameters via property assignments as follows:
13 | %
14 | % obj = PeakFit(); % creates an empty PeakFit
15 | % obj.XData = [...]; % specify the X data points
16 | % obj.YData = [...]; % specify the Y data points
17 | % obj.CenterStart = [...]; % specify the start points of the peak centers
18 | % obj.WidthStart = [...]; % specify the start points for the peak widths
19 | %
20 | % To perform the peak fitting, call another PeakFit with the prepared obj
21 | % as the input argument:
22 | %
23 | % obj = PeakFit(obj);
24 | %
25 | % The fit results will be stored in the object properties, which can be
26 | % displayed into the console by calling:
27 | %
28 | % disp(obj);
29 | %
30 | % The second is by specifying the data points and fitting parameters
31 | % together in one call as follows:
32 | %
33 | % obj = PeakFit(Data, ...
34 | % Window, [...], ...
35 | % CenterLow, [...], ...
36 | % CenterUp, [...], ...
37 | % WidthUp, [...], ...
38 | % BaselinePolyOrder, [.]);
39 | %
40 | % The data points can also be specified in the following way:
41 | %
42 | % obj = PeakFit(XData, YData, ...);
43 | %
44 | % The peak fitting will be performed automatically after the object
45 | % construction, provided that the data points have been supplied. The data
46 | % points are the only mandatory inputs for a PeakFit object.
47 | %
48 | % In most cases, specifying the following parameters: Window, CenterLow,
49 | % CenterUp, WidthUp, and BaselinePolyOrder, would improve the accuracy of
50 | % the peak fitting significantly.
51 | %
52 | % Public Properties:
53 | % Data: The data points of the curve. An alternative to XData and YData.
54 | % Data must be a two-column or two-row matrix.
55 | %
56 | % XData: The X data points of the curve.
57 | %
58 | % YData: The Y data points of the curve. The peak fitting may not work
59 | % properly if some Y data points are negative.
60 | %
61 | % Window: A vector of length two [a,b] that limits the fitting to only the
62 | % data points whose X coordinates lies within [a,b].
63 | %
64 | % NumPeaks: The number of peaks wished to be fitted. When the fitting peak
65 | % shape, start point, lower, or upper bound are set with vectors
66 | % of length greater than NumPeaks, then NumPeaks will be
67 | % incremented to adjust to the maximum length of these vectors.
68 | % When the maximum length of these vectors is less, then these
69 | % vectors will be expanded and filled with the default values.
70 | % When NumPeaks=0 and all the start point, lower, and upper are
71 | % not set, then the program attempts to fit all peaks found in
72 | % the curve.
73 | %
74 | % PeakShape: A string vector that specifies the peak shape of each peak.
75 | % Available PeakShape in this version are: 'Lorentzian' (1) and
76 | % 'Gaussian' (2). PeakShape may be set with an integer, the
77 | % initial of these names, e.g. 'L' or 'G', or the full name,
78 | % e.g. 'Lorentzian'. When the length of PeakShape is less than
79 | % NumPeaks, the remaining peaks will have a default PeakShape,
80 | % which is 'Lorentzian'. If PeakShape contains only one
81 | % element, then the default value is the same as that element.
82 | %
83 | % BaselinePolyOrder: An integer that specifies the order of the polynomial
84 | % function used to fit the background of the spectrum.
85 | % Defaults to 0 (a constant polynomial). Set this to a
86 | % negative value to exclude the polynomial from the fit
87 | % model.
88 | %
89 | % ...Start: A vector of initial values for the ... coefficients, where the
90 | % blanks are one of the {Area, Center, Width, Height, Baseline}.
91 | % The default values are determined heuristically. To make
92 | % certain properties default, set their values to NaN. They will
93 | % be then replaced with the default values upon fitting.
94 | %
95 | % ...Low: A vector of lower bounds for the ... coefficients, where the
96 | % blanks are one of the {Area, Center, Width, Height, Baseline}.
97 | % The default values are determined heuristically. To make certain
98 | % properties default, set their values to -Inf. They will be then
99 | % replaced with the default values upon fitting.
100 | %
101 | % ...Up: A vector of upper bounds for the ... coefficients, where the
102 | % blanks are one of the {Area, Center, Width, Height, Baseline}.
103 | % The default values are determined heuristically. To make certain
104 | % properties default, set their values to Inf. They will be then
105 | % replaced with the default values upon fitting.
106 | %
107 | % Robust: The type of the least-squares method to be used in the fitting.
108 | % Available values are 'off', 'LAR' (least absolute residual), and
109 | % 'Bisquare' (bisquare weights). Defaults to 'off'.
110 | %
111 | % Algorithm: The algorithm to be used in the fitting. Available values are
112 | % 'Lavenberg-Marquardt', 'Gauss-Newton', or 'Trust-Region'.
113 | % Defaults to 'Trust-Region'.
114 | %
115 | % MovMeanWidth: The window width of the moving average used for smoothing
116 | % the curve in order to filter out the noise before finding
117 | % the maximas. This parameter is used only when CenterStart
118 | % is not given. The value of this can be set as a positive
119 | % integer which specifies the width in terms of the number
120 | % of data points, OR a real scalar between [0,1] which
121 | % specifies the width as a fraction of the total number of
122 | % data points.
123 | %
124 | % DiffMaxChange: The maximum change in coefficients for finite difference
125 | % gradients. Defaults to 0.1.
126 | %
127 | % DiffMinChange: The minimum change in coefficients for finite difference
128 | % gradients. Defaults to 1e-8.
129 | %
130 | % MaxFunEvals: The allowed maximum number of evaluations of the model.
131 | % Defaults to 1e5.
132 | %
133 | % MaxIters: The maximum number of iterations allowed for the fit. Defaults
134 | % to 1e3.
135 | %
136 | % TolFun: The termination tolerance on the model value. Defaults to 10^-6.
137 | %
138 | % TolX: The termination tolerance on the coefficient values. Defaults to
139 | % 10^-6.
140 | %
141 | % Read-only Properties:
142 | % Method: The method used for the fitting, which is
143 | % 'NonLinearLeastSquares'.
144 | %
145 | % Peak: A struct containing the fit results for each peak.
146 | %
147 | % Base: A struct containing the fit results for the baseline.
148 | %
149 | % Area, Center, Height, Width, Baseline: A 3-by-NumPeaks matrix that
150 | % stores the fit results for the area,... , respectively. The first
151 | % row is the values at convergence; the second row is the 95% CI
152 | % lower bounds; and the third row is the 95% CI upper bounds.
153 | %
154 | % RelStDev: The relative standard deviation of the fit results.
155 | %
156 | % CoeffDeterm: The coefficient of determination of the fit results.
157 | %
158 | % AdjCoeffDeterm: The degree-of-freedom adjusted coefficient of
159 | % determination of the fit results.
160 | %
161 | % NumFunEvals: The number of function evaluations.
162 | %
163 | % NumIters: The number of iterations.
164 | %
165 | % ExitFlag: The exit condition of the algorithm. Positive flags indicate
166 | % convergence, within tolerances. Zero flags indicate that the
167 | % maximum number of function evaluations or iterations was
168 | % exceeded. Negative flags indicate that the algorithm did not
169 | % converge to a solution.
170 | %
171 | % Public Methods:
172 | % disp: Displays the options, results, error and performance of the
173 | % fitting.
174 | %
175 | % model: Returns the reconstructed data points (model) using the fit
176 | % results.
177 | %
178 | % convertunit: Converts the units of the data points and the fit results.
179 | % Available units to be converted from or to are:
180 | % 'eV' : electron volt
181 | % 'percm' : cm^{-1} (wavenumber)
182 | % 'Ramanshift': cm^{-1} (Raman shift)
183 | % When converting to or from Raman shift, an additional
184 | % argument is required that specifies the excitation
185 | % wavelength in nanometer.
186 | %
187 | % Static Methods:
188 | % fnlorentzian: The lorentzian function.
189 | %
190 | % fngaussian: The gaussian function.
191 | %
192 | % Requires package:
193 | % - MatCommon_v1.0.0+
194 | % - PhysConst_v1.0.0+ (for the convertunit method only)
195 | %
196 | % Tested on:
197 | % - MATLAB R2013b
198 | % - MATLAB R2015b
199 | % - MATLAB R2017b
200 | % - MATLAB R2018a
201 | %
202 | % Copyright: Herianto Lim (https://heriantolim.com)
203 | % Licensing: GNU General Public License v3.0
204 | % First created: 25/03/2013
205 | % Last modified: 04/11/2016
206 |
207 | %% Properties
208 | % Data, start points, and constraints for fitting
209 | properties (Dependent = true)
210 | Data
211 | end
212 |
213 | properties
214 | XData
215 | YData
216 | Window
217 | NumPeaks = 0;
218 | PeakShape
219 | AreaStart
220 | AreaLow
221 | AreaUp
222 | CenterStart
223 | CenterLow
224 | CenterUp
225 | HeightStart
226 | HeightLow
227 | HeightUp
228 | WidthStart
229 | WidthLow
230 | WidthUp
231 | BaselinePolyOrder = 0;
232 | end
233 |
234 | % The start point and constraints for the baseline are set automatically
235 | properties (SetAccess = protected)
236 | BaselineStart
237 | BaselineLow
238 | BaselineUp
239 | end
240 |
241 | % Fitting options
242 | properties (Constant = true)
243 | Method = 'NonlinearLeastSquares';
244 | end
245 |
246 | properties
247 | Robust = 'off';
248 | Algorithm = 'Trust-Region';
249 | MovMeanWidth = .02;
250 | DiffMaxChange = .1;
251 | DiffMinChange = 1e-8;
252 | MaxFunEvals = 1e5;
253 | MaxIters = 1e3;
254 | TolFun = 1e-6;
255 | TolX = 1e-6;
256 | end
257 |
258 | % Fit results
259 | properties (SetAccess = protected)
260 | Center
261 | Height
262 | Width
263 | Baseline
264 | end
265 |
266 | properties (Dependent = true)
267 | Area
268 | Peak
269 | Base
270 | end
271 |
272 | % Fit errors and performance
273 | properties (SetAccess = protected)
274 | RelStDev = 0;
275 | CoeffDeterm = 0;
276 | AdjCoeffDeterm = 0;
277 | NumFunEvals = 0;
278 | NumIters = 0;
279 | ExitFlag
280 | end
281 |
282 | % Class dictionary
283 | properties (Constant = true, GetAccess = protected)
284 | DefaultPeakShape = 1;
285 | MinNumPoints = 10;
286 | PeakShapeTable = table(...
287 | [1; 2], ...
288 | {'L'; 'G'}, ...
289 | {'Lorentzian'; 'Gaussian'}, ...
290 | 'VariableNames', {'ID', 'Initial', 'Name'});
291 | RobustList = {'on', 'off', 'LAR', 'Bisquare'};
292 | AlgorithmList = {'Levenberg-Marquardt', 'Trust-Region'};
293 | end
294 |
295 | %% Methods
296 | methods
297 | % Constructor
298 | function obj = PeakFit(varargin)
299 | N = nargin;
300 |
301 | if N == 0
302 | return
303 | end
304 |
305 | % Copy the PeakFit object given in the first argument if any
306 | k = 1;
307 |
308 | if isa(varargin{k}, class(obj))
309 | obj = varargin{k};
310 | k = k + 1;
311 | end
312 |
313 | % Parse input to Data points
314 | if k <= N && isrealmatrix(varargin{k})
315 |
316 | if isvector(varargin{k})
317 |
318 | if k < N && isrealvector(varargin{k + 1})
319 | obj.XData = varargin{k};
320 | obj.YData = varargin{k + 1};
321 | k = k + 2;
322 | end
323 |
324 | else
325 | obj.Data = varargin{k};
326 | k = k + 1;
327 | end
328 |
329 | end
330 |
331 | % Parse inputs to the parameters
332 | P = properties(obj);
333 |
334 | while k < N
335 |
336 | if ~isstringscalar(varargin{k})
337 | break
338 | end
339 |
340 | ix = strcmpi(varargin{k}, P);
341 |
342 | if any(ix)
343 | obj.(P{ix}) = varargin{k + 1};
344 | k = k + 2;
345 | else
346 | break
347 | end
348 |
349 | end
350 |
351 | assert(k > N, ...
352 | 'PeakFit:UnexpectedInput', ...
353 | 'One or more inputs are not recognized.');
354 |
355 | % Perform peak fitting
356 | obj = fit(obj);
357 | end
358 |
359 | % Get Methods
360 | function x = get.Data(obj)
361 |
362 | if numel(obj.XData) == numel(obj.YData)
363 | x = [obj.XData; obj.YData];
364 | else
365 | x = [];
366 | end
367 |
368 | end
369 |
370 | function x = get.Area(obj)
371 | peakShape = obj.PeakShape;
372 | height = obj.Height;
373 | width = obj.Width;
374 |
375 | if isempty(peakShape) || isempty(height) || isempty(width)
376 | x = [];
377 | else
378 | numPeaks = numel(peakShape);
379 | x = zeros(3, numPeaks);
380 |
381 | for i = 1:numPeaks
382 | x(:, i) = PeakFit.computearea(peakShape(i), ...
383 | height(:, i), width(:, i));
384 | end
385 |
386 | end
387 |
388 | end
389 |
390 | function x = get.Peak(obj)
391 | x = struct();
392 | area = obj.Area;
393 | center = obj.Center;
394 | height = obj.Height;
395 | width = obj.Width;
396 |
397 | if isempty(area) || isempty(center) || isempty(height) || isempty(width)
398 | return
399 | end
400 |
401 | numPeaks = obj.NumPeaks;
402 |
403 | for i = 1:numPeaks
404 | x(i).Area.Value = area(1, i);
405 | x(i).Area.CI = area(2:3, i).';
406 | x(i).Center.Value = center(1, i);
407 | x(i).Center.CI = center(2:3, i).';
408 | x(i).Height.Value = height(1, i);
409 | x(i).Height.CI = height(2:3, i).';
410 | x(i).Width.Value = width(1, i);
411 | x(i).Width.CI = width(2:3, i).';
412 | end
413 |
414 | end
415 |
416 | function x = get.Base(obj)
417 | x = struct();
418 | baseline = obj.Baseline;
419 |
420 | if ~isempty(baseline)
421 | P = obj.BaselinePolyOrder;
422 | Q = P + 1;
423 |
424 | for i = 1:Q
425 | x.(sprintf('p%d', i)).Value = baseline(1, i);
426 | x.(sprintf('p%d', i)).CI = baseline(2:3, i).';
427 | end
428 |
429 | end
430 |
431 | end
432 |
433 | % Set Methods
434 | function obj = set.Data(obj, x)
435 |
436 | if isempty(x)
437 | obj.XData = [];
438 | obj.YData = [];
439 | return
440 | end
441 |
442 | ME = MException('PeakFit:InvalidInput', ...
443 | 'Input to set the Data must be a real matrix of size [n,2] or [2,n].');
444 |
445 | if isrealmatrix(x)
446 | [m, n] = size(x);
447 |
448 | if m == 2
449 | obj.XData = x(1, :);
450 | obj.YData = x(2, :);
451 | elseif n == 2
452 | obj.XData = x(:, 1);
453 | obj.YData = x(:, 2);
454 | else
455 | throw(ME);
456 | end
457 |
458 | else
459 | throw(ME);
460 | end
461 |
462 | end
463 |
464 | function obj = set.XData(obj, x)
465 |
466 | if isempty(x)
467 | obj.XData = [];
468 | elseif isrealvector(x) && all(isfinite(x))
469 |
470 | if numel(x) < obj.MinNumPoints
471 | error('PeakFit:setXData:InsufficientNumPoints', ...
472 | 'Input vector to the XData must have at least %d elements.', ...
473 | obj.MinNumPoints);
474 | else
475 | obj.XData = x(:).';
476 | end
477 |
478 | else
479 | error('PeakFit:setXData:InvalidInput', ...
480 | 'Input to set the XData must be a vector of finite real numbers.');
481 | end
482 |
483 | end
484 |
485 | function obj = set.YData(obj, x)
486 |
487 | if isempty(x)
488 | obj.YData = [];
489 | elseif isrealvector(x) && all(isfinite(x))
490 |
491 | if numel(x) < obj.MinNumPoints
492 | error('PeakFit:setYData:InsufficientNumPoints', ...
493 | 'Input vector to the YData must have at least %d elements.', ...
494 | obj.MinNumPoints);
495 | else
496 | obj.YData = x(:).';
497 | end
498 |
499 | else
500 | error('PeakFit:setYData:InvalidInput', ...
501 | 'Input to set the YData must be a vector of finite real numbers.');
502 | end
503 |
504 | end
505 |
506 | function obj = set.Window(obj, x)
507 |
508 | if isempty(x)
509 | obj.Window = [];
510 | elseif isrealvector(x) && numel(x) == 2
511 | obj.Window = sort(x(:)).';
512 | else
513 | error('PeakFit:setWindow:InvalidInput', ...
514 | 'Input to set the Window must be a real vector of length two.');
515 | end
516 |
517 | end
518 |
519 | function obj = set.NumPeaks(obj, x)
520 |
521 | if isintegerscalar(x) && x >= 0
522 | obj.NumPeaks = x;
523 | else
524 | error('PeakFit:setNumPeaks:InvalidInput', ...
525 | 'Input to set the NumPeaks must be a positive integer scalar.');
526 | end
527 |
528 | end
529 |
530 | function obj = set.PeakShape(obj, x)
531 |
532 | if isempty(x)
533 | obj.PeakShape = [];
534 | elseif isintegervector(x)
535 | obj.PeakShape = x(:).';
536 | else
537 |
538 | if isstringscalar(x)
539 | x = {x};
540 | elseif ~isstringvector(x)
541 | error('PeakFit:setPeakShape:InvalidInput', ...
542 | 'Input to PeakShape must be a string scalar or vector.');
543 | end
544 |
545 | ME = MException('PeakFit:setPeakShape:UnexpectedInput', ...
546 | 'The specified peak shape has not been defined in this class.');
547 | N = numel(x);
548 | y = zeros(1, N);
549 |
550 | for n = 1:N
551 |
552 | if numel(x{n}) == 1
553 | tf = strcmpi(x{n}, obj.PeakShapeTable.Initial);
554 | else
555 | tf = strcmpi(x{n}, obj.PeakShapeTable.Name);
556 | end
557 |
558 | if any(tf)
559 | y(n) = obj.PeakShapeTable.ID(tf);
560 | else
561 | throw(ME);
562 | end
563 |
564 | end
565 |
566 | obj.PeakShape = y;
567 | end
568 |
569 | end
570 |
571 | function obj = set.AreaStart(obj, x)
572 |
573 | if isempty(x)
574 | obj.AreaStart = [];
575 | elseif isrealvector(x)
576 | obj.AreaStart = x(:).';
577 | else
578 | error('PeakFit:setAreaStart:InvalidInput', ...
579 | 'Input to set the AreaStart must be a vector of real numbers.');
580 | end
581 |
582 | end
583 |
584 | function obj = set.AreaLow(obj, x)
585 |
586 | if isempty(x)
587 | obj.AreaLow = [];
588 | elseif isrealvector(x)
589 | obj.AreaLow = x(:).';
590 | else
591 | error('PeakFit:setAreaLow:InvalidInput', ...
592 | 'Input to set the AreaLow must be a vector of real numbers.');
593 | end
594 |
595 | end
596 |
597 | function obj = set.AreaUp(obj, x)
598 |
599 | if isempty(x)
600 | obj.AreaUp = [];
601 | elseif isrealvector(x)
602 | obj.AreaUp = x(:).';
603 | else
604 | error('PeakFit:setAreaUp:InvalidInput', ...
605 | 'Input to set the AreaUp must be a vector of real numbers.');
606 | end
607 |
608 | end
609 |
610 | function obj = set.CenterStart(obj, x)
611 |
612 | if isempty(x)
613 | obj.CenterStart = [];
614 | elseif isrealvector(x)
615 | obj.CenterStart = x(:).';
616 | else
617 | error('PeakFit:setCenterStart:InvalidInput', ...
618 | 'Input to set the CenterStart must be a vector of real numbers.');
619 | end
620 |
621 | end
622 |
623 | function obj = set.CenterLow(obj, x)
624 |
625 | if isempty(x)
626 | obj.CenterLow = [];
627 | elseif isrealvector(x)
628 | obj.CenterLow = x(:).';
629 | else
630 | error('PeakFit:setCenterLow:InvalidInput', ...
631 | 'Input to set the CenterLow must be a vector of real numbers.');
632 | end
633 |
634 | end
635 |
636 | function obj = set.CenterUp(obj, x)
637 |
638 | if isempty(x)
639 | obj.CenterUp = [];
640 | elseif isrealvector(x)
641 | obj.CenterUp = x(:).';
642 | else
643 | error('PeakFit:setCenterUp:InvalidInput', ...
644 | 'Input to set the CenterUp must be a vector of real numbers.');
645 | end
646 |
647 | end
648 |
649 | function obj = set.HeightStart(obj, x)
650 |
651 | if isempty(x)
652 | obj.HeightStart = [];
653 | elseif isrealvector(x)
654 | obj.HeightStart = x(:).';
655 | else
656 | error('PeakFit:setHeightStart:InvalidInput', ...
657 | 'Input to set the HeightStart must be a vector of real numbers.');
658 | end
659 |
660 | end
661 |
662 | function obj = set.HeightLow(obj, x)
663 |
664 | if isempty(x)
665 | obj.HeightLow = [];
666 | elseif isrealvector(x)
667 | obj.HeightLow = x(:).';
668 | else
669 | error('PeakFit:setHeightLow:InvalidInput', ...
670 | 'Input to set the HeightLow must be a vector of real numbers.');
671 | end
672 |
673 | end
674 |
675 | function obj = set.HeightUp(obj, x)
676 |
677 | if isempty(x)
678 | obj.HeightUp = [];
679 | elseif isrealvector(x)
680 | obj.HeightUp = x(:).';
681 | else
682 | error('PeakFit:setHeightUp:InvalidInput', ...
683 | 'Input to set the HeightUp must be a vector of real numbers.');
684 | end
685 |
686 | end
687 |
688 | function obj = set.WidthStart(obj, x)
689 |
690 | if isempty(x)
691 | obj.WidthStart = [];
692 | elseif isrealvector(x) && all(isnan(x) | x >= 0)
693 | obj.WidthStart = x(:).';
694 | else
695 | error('PeakFit:setWidthStart:InvalidInput', ...
696 | 'Input to set the WidthStart must be a vector of positive real numbers.');
697 | end
698 |
699 | end
700 |
701 | function obj = set.WidthLow(obj, x)
702 |
703 | if isempty(x)
704 | obj.WidthLow = [];
705 | elseif isrealvector(x) && all(isnan(x) | x >= 0)
706 | obj.WidthLow = x(:).';
707 | else
708 | error('PeakFit:setWidthLow:InvalidInput', ...
709 | 'Input to set the WidthLow must be a vector of positive real numbers.');
710 | end
711 |
712 | end
713 |
714 | function obj = set.WidthUp(obj, x)
715 |
716 | if isempty(x)
717 | obj.WidthUp = [];
718 | elseif isrealvector(x) && all(isnan(x) | x >= 0)
719 | obj.WidthUp = x(:).';
720 | else
721 | error('PeakFit:setWidthUp:InvalidInput', ...
722 | 'Input to set the WidthUp must be a vector of positive real numbers.');
723 | end
724 |
725 | end
726 |
727 | function obj = set.BaselinePolyOrder(obj, x)
728 |
729 | if isintegerscalar(x)
730 | obj.BaselinePolyOrder = x;
731 | else
732 | error('PeakFit:setBaselinePolyOrder:InvalidInput', ...
733 | 'Input to set the BaselinePolyOrder must be an integer scalar.');
734 | end
735 |
736 | end
737 |
738 | function obj = set.BaselineStart(obj, x)
739 |
740 | if isempty(x)
741 | obj.BaselineStart = [];
742 | elseif isrealvector(x)
743 | obj.BaselineStart = x(:).';
744 | else
745 | error('PeakFit:setBaselineStart:InvalidInput', ...
746 | 'Input to set the BaselineStart must be a vector of real numbers.');
747 | end
748 |
749 | end
750 |
751 | function obj = set.BaselineLow(obj, x)
752 |
753 | if isempty(x)
754 | obj.BaselineLow = [];
755 | elseif isrealvector(x)
756 | obj.BaselineLow = x(:).';
757 | else
758 | error('PeakFit:setBaselineLow:InvalidInput', ...
759 | 'Input to set the BaselineLow must be a vector of real numbers.');
760 | end
761 |
762 | end
763 |
764 | function obj = set.BaselineUp(obj, x)
765 |
766 | if isempty(x)
767 | obj.BaselineUp = [];
768 | elseif isrealvector(x)
769 | obj.BaselineUp = x(:).';
770 | else
771 | error('PeakFit:setBaselineUp:InvalidInput', ...
772 | 'Input to set the BaselineUp must be a vector of real numbers.');
773 | end
774 |
775 | end
776 |
777 | function obj = set.Robust(obj, x)
778 | ME = MException('PeakFit:setRobust:InvalidInput', ...
779 | 'Input to set the Robust must be either: %s.', ...
780 | strjoin(obj.RobustList, ', '));
781 |
782 | if isstringscalar(x)
783 | tf = strcmpi(x, obj.RobustList);
784 |
785 | if any(tf)
786 | obj.Robust = obj.RobustList{tf};
787 | else
788 | throw(ME);
789 | end
790 |
791 | else
792 | throw(ME);
793 | end
794 |
795 | end
796 |
797 | function obj = set.Algorithm(obj, x)
798 | ME = MException('PeakFit:setAlgorithm:InvalidInput', ...
799 | 'Input to set the Algorithm must be either: %s.', ...
800 | strjoin(obj.AlgorithmList, ', '));
801 |
802 | if isstringscalar(x)
803 | tf = strcmpi(x, obj.AlgorithmList);
804 |
805 | if any(tf)
806 | obj.Algorithm = obj.AlgorithmList{tf};
807 | else
808 | throw(ME);
809 | end
810 |
811 | else
812 | throw(ME);
813 | end
814 |
815 | end
816 |
817 | function obj = set.MovMeanWidth(obj, x)
818 | ME = MException('PeakFit:setMovMeanWidth:InvalidInput', ...
819 | 'Input to set the MovMeanWidth must be a positive integer scalar or a real scalar between [0,1].');
820 |
821 | if isrealscalar(x) && x >= 0
822 |
823 | if isintegerscalar(x) || x <= 1
824 | obj.MovMeanWidth = x;
825 | else
826 | throw(ME);
827 | end
828 |
829 | else
830 | throw(ME);
831 | end
832 |
833 | end
834 |
835 | function obj = set.DiffMaxChange(obj, x)
836 |
837 | if isrealscalar(x) && x > 0
838 | obj.DiffMaxChange = x;
839 | else
840 | error('PeakFit:setDiffMaxChange:InvalidInput', ...
841 | 'Input to set the DiffMaxChange must be a positive real scalar.');
842 | end
843 |
844 | end
845 |
846 | function obj = set.DiffMinChange(obj, x)
847 |
848 | if isrealscalar(x) && x > 0
849 | obj.DiffMinChange = x;
850 | else
851 | error('PeakFit:setDiffMinChange:InvalidInput', ...
852 | 'Input to set the DiffMinChange must be a positive real scalar.');
853 | end
854 |
855 | end
856 |
857 | function obj = set.MaxFunEvals(obj, x)
858 |
859 | if isintegerscalar(x) && x > 0
860 | obj.MaxFunEvals = x;
861 | else
862 | error('PeakFit:setMaxFunEvals:InvalidInput', ...
863 | 'Input to set the MaxFunEvals must be a positive integer scalar.');
864 | end
865 |
866 | end
867 |
868 | function obj = set.MaxIters(obj, x)
869 |
870 | if isintegerscalar(x) && x > 0
871 | obj.MaxIters = x;
872 | else
873 | error('PeakFit:setMaxIters:InvalidInput', ...
874 | 'Input to set the MaxIters must be a positive integer scalar.');
875 | end
876 |
877 | end
878 |
879 | function obj = set.TolFun(obj, x)
880 |
881 | if isrealscalar(x) && x > 0
882 | obj.TolFun = x;
883 | else
884 | error('PeakFit:setTolFun:InvalidInput', ...
885 | 'Input to set the TolFun must be a positive real scalar.');
886 | end
887 |
888 | end
889 |
890 | function obj = set.TolX(obj, x)
891 |
892 | if isrealscalar(x) && x > 0
893 | obj.TolX = x;
894 | else
895 | error('PeakFit:setTolX:InvalidInput', ...
896 | 'Input to set the TolX must be a positive real scalar.');
897 | end
898 |
899 | end
900 |
901 | function obj = set.Center(obj, x)
902 |
903 | if ~isempty(x)
904 |
905 | if isrealmatrix(x) && size(x, 1) == 3
906 | obj.Center = x;
907 | else
908 | error('PeakFit:setCenter:InvalidInput', ...
909 | 'Input to set the Center must be a real matrix with 3 rows.');
910 | end
911 |
912 | end
913 |
914 | end
915 |
916 | function obj = set.Height(obj, x)
917 |
918 | if ~isempty(x)
919 |
920 | if isrealmatrix(x) && size(x, 1) == 3
921 | obj.Height = x;
922 | else
923 | error('PeakFit:setHeight:InvalidInput', ...
924 | 'Input to set the Height must be a real matrix with 3 rows.');
925 | end
926 |
927 | end
928 |
929 | end
930 |
931 | function obj = set.Width(obj, x)
932 |
933 | if ~isempty(x)
934 |
935 | if isrealmatrix(x) && size(x, 1) == 3
936 | obj.Width = x;
937 | else
938 | error('PeakFit:setWidth:InvalidInput', ...
939 | 'Input to set the Width must be a real matrix with 3 rows.');
940 | end
941 |
942 | end
943 |
944 | end
945 |
946 | function obj = set.Baseline(obj, x)
947 |
948 | if ~isempty(x)
949 |
950 | if isrealmatrix(x) && size(x, 1) == 3
951 | obj.Baseline = x;
952 | else
953 | error('PeakFit:setBaseline:InvalidInput', ...
954 | 'Input to set the Baseline must be a real matrix with 3 rows.');
955 | end
956 |
957 | end
958 |
959 | end
960 |
961 | function obj = set.RelStDev(obj, x)
962 |
963 | if isrealscalar(x) && x >= 0
964 | obj.RelStDev = x;
965 | else
966 | error('PeakFit:setRelStDev:InvalidInput', ...
967 | 'Input to set the RelStDev must be a positive real scalar.');
968 | end
969 |
970 | end
971 |
972 | function obj = set.CoeffDeterm(obj, x)
973 |
974 | if isrealscalar(x)
975 | obj.CoeffDeterm = x;
976 | else
977 | error('PeakFit:setCoeffDeterm:InvalidInput', ...
978 | 'Input to set the CoeffDeterm must be a real scalar.');
979 | end
980 |
981 | end
982 |
983 | function obj = set.AdjCoeffDeterm(obj, x)
984 |
985 | if isrealscalar(x)
986 | obj.AdjCoeffDeterm = x;
987 | else
988 | error('PeakFit:setAdjCoeffDeterm:InvalidInput', ...
989 | 'Input to set the AdjCoeffDeterm must be a real scalar.');
990 | end
991 |
992 | end
993 |
994 | function obj = set.NumFunEvals(obj, x)
995 |
996 | if isintegerscalar(x) && x >= 0
997 | obj.NumFunEvals = x;
998 | else
999 | error('PeakFit:setNumFunEvals:InvalidInput', ...
1000 | 'Input to set the NumFunEvals must be a positive integer scalar.');
1001 | end
1002 |
1003 | end
1004 |
1005 | function obj = set.NumIters(obj, x)
1006 |
1007 | if isintegerscalar(x) && x >= 0
1008 | obj.NumIters = x;
1009 | else
1010 | error('PeakFit:setNumIters:InvalidInput', ...
1011 | 'Input to set the NumIters must be a positive integer scalar.');
1012 | end
1013 |
1014 | end
1015 |
1016 | function obj = set.ExitFlag(obj, x)
1017 |
1018 | if isempty(x)
1019 | obj.ExitFlag = [];
1020 | elseif isintegerscalar(x)
1021 | obj.ExitFlag = x;
1022 | else
1023 | error('PeakFit:setExitFlag:InvalidInput', ...
1024 | 'Input to set the ExitFlag must be an integer scalar.');
1025 | end
1026 |
1027 | end
1028 |
1029 | % display the object properties
1030 | disp(obj)
1031 |
1032 | % construct a fit model from the fit results
1033 | [yModel, yPeak, yBaseline] = model(obj, varargin)
1034 |
1035 | % convert units
1036 | obj = convertunit(obj, unitFrom, unitTo, varargin)
1037 | end
1038 |
1039 | methods (Access = protected)
1040 | % fit peaks
1041 | obj = fit(obj)
1042 |
1043 | % find maxima
1044 | [xm, ym] = findmaxima(obj, varargin)
1045 | end
1046 |
1047 | methods (Static = true)
1048 | % lorentzian function
1049 | y = fnlorentzian(x, c, h, w)
1050 |
1051 | % gaussian function
1052 | y = fngaussian(x, c, h, w)
1053 | end
1054 |
1055 | methods (Static = true, Access = protected)
1056 | % compute the peak area
1057 | area = computearea(peakShape, height, width)
1058 |
1059 | % compute the peak height
1060 | height = computeheight(peakShape, area, width)
1061 |
1062 | % compute the peak width
1063 | width = computewidth(peakShape, area, height)
1064 |
1065 | % transform polynomial coefficients
1066 | p = transformpolycoeff(p, varargin)
1067 | end
1068 |
1069 | end
1070 |
--------------------------------------------------------------------------------