A titolo di esempio, si immagini di avere i dati sperimentali
A titolo di esempio, si immagini di avere i dati sperimentali
A titolo di esempio, si immagini di avere i dati sperimentali
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
FITTING <strong>di</strong> <strong>dati</strong> <strong>sperimentali</strong><br />
un <strong>esempio</strong><br />
A <strong>titolo</strong> <strong>di</strong> <strong>esempio</strong>, <strong>si</strong> <strong>immagini</strong> <strong>di</strong> <strong>avere</strong> i <strong>dati</strong> <strong>sperimentali</strong><br />
Xdata, Ydata nonché l’errore associato eYdata<br />
Su questi <strong>dati</strong> <strong>si</strong> vuole fittare un modello del tipo Y=A+B*X+C*X 2<br />
Di seguito riporto una procedura Matlab che genera i <strong>dati</strong> (secondo il modello + rumore) e poi ci<br />
fitta il modello dato minimizzando una funzione che calcola il χ 2 del fit. La minimizzazione può<br />
essere fatta <strong>si</strong>a usando il comando <strong>di</strong> Matlab FMINSEARCH , che generalmente è sufficiente,<br />
<strong>si</strong>a usando il molto più sofisticato e potente pacchetto <strong>di</strong> funzioni <strong>di</strong> FMINUIT (della libreria <strong>di</strong><br />
routines CERNlibrary) così come è stato interfacciato nell’ambiente Matlab da G. Allo<strong>di</strong>.<br />
Fminsearch restituisce i parametri che danno il miglior fit ed il χ 2 del fit.<br />
In aggiunta Fminuit può restituire l’accuratezza della stima <strong>di</strong> ciascun parametro. Inoltre consente <strong>di</strong><br />
seguire strategia <strong>di</strong> minimizzazione <strong>di</strong>verse, e <strong>di</strong> chiamare la funzione minimizzanda per eseguire<br />
dei plot interme<strong>di</strong>.<br />
PROCEDURA MATLAB:<br />
clear all<br />
Xdata=[0:.05:5]';<br />
Ydata=-.2+.1*Xdata+2.5*Xdata.^2;<br />
NOISE=.1; %rumore sperimentale che affligge le misure Ydata<br />
Ydata=Ydata+NOISE*randn(<strong>si</strong>ze(Ydata));<br />
eYdata=zeros(<strong>si</strong>ze(Ydata))+NOISE;<br />
data=[Xdata,Ydata,eYdata];<br />
figure(1)<br />
clf<br />
errorbar(Xdata,Ydata,eYdata/2,eYdata/2,'.');<br />
pause<br />
startpar=[-.1 .1 1];<br />
%[bestpar,chival]=fminsearch('chi2',startpar,[],data)<br />
[bestpar,ebestpar,chival]=fminuit('chi2',startpar,[],data)<br />
hold on<br />
plot(Xdata,bestpar(1)+bestpar(2)*Xdata+bestpar(3)*Xdata.^2,'-k');<br />
FUNZIONE χ 2 DA MINIMIZZARE:<br />
function chi2=chi2(parametri, data)<br />
%Calcola il Chi2 ridotto (Taylor, 12.2 pag 186)<br />
A=parametri(1);<br />
B=parametri(2);<br />
C=parametri(3);<br />
Xdata=data(:,1);<br />
Ydata=data(:,2);<br />
eYdata=data(:,3);<br />
N=length(Xdata); %Numero <strong>di</strong> osservazioni<br />
p=length(parametri); %Numero <strong>di</strong> parametri del fit<br />
model=A + B*Xdata + C*Xdata .^2 ;<br />
chi2=sum ( (model - Ydata ).^2 ./ eYdata.^2 ) / (N-p);
HELP DELLA FUNZIONE FMINSEARCH<br />
(<strong>di</strong>sponibile anche on<strong>di</strong>ne dentro a Matlab)<br />
FMINSEARCH Multi<strong>di</strong>men<strong>si</strong>onal unconstrained nonlinear minimization (Nelder-Mead).<br />
X = FMINSEARCH(FUN,X0) starts at X0 and finds a local minimizer X of the<br />
function FUN. FUN accepts input X and returns a scalar function value<br />
F evaluated at X. X0 can be a scalar, vector or matrix.<br />
X = FMINSEARCH(FUN,X0,OPTIONS) minimizes with the default optimization<br />
parameters replaced by values in the structure OPTIONS, created<br />
with the OPTIMSET function. See OPTIMSET for details. FMINSEARCH uses<br />
these options: Display, TolX, TolFun, MaxFunEvals, and MaxIter.<br />
X = FMINSEARCH(FUN,X0,OPTIONS,P1,P2,...) provides for ad<strong>di</strong>tional<br />
arguments which are passed to the objective function,<br />
F=feval(FUN,X,P1,P2,...).<br />
Pass an empty matrix for OPTIONS to use the default values.<br />
(Use OPTIONS = [] as a place holder if no options are set.)<br />
[X,FVAL]= FMINSEARCH(...) returns the value of the objective function,<br />
described in FUN, at X.<br />
[X,FVAL,EXITFLAG] = FMINSEARCH(...) returns a string EXITFLAG that<br />
describes the exit con<strong>di</strong>tion of FMINSEARCH.<br />
If EXITFLAG is:<br />
1 then FMINSEARCH converged with a solution X.<br />
0 then the maximum number of iterations was reached.<br />
[X,FVAL,EXITFLAG,OUTPUT] = FMINSEARCH(...) returns a structure<br />
OUTPUT with the number of iterations taken in OUTPUT.iterations.<br />
Examples<br />
FUN can be specified u<strong>si</strong>ng @:<br />
X = fminsearch(@<strong>si</strong>n,3)<br />
finds a minimum of the SIN function near 3.<br />
In this case, SIN is a function that returns a scalar function value<br />
SIN evaluated at X.<br />
FUN can also be an inline object:<br />
X = fminsearch(inline('norm(x)'),[1;2;3])<br />
returns a minimum near [0;0;0].<br />
FMINSEARCH uses the Nelder-Mead <strong>si</strong>mplex (<strong>di</strong>rect search) method.<br />
See also OPTIMSET, FMINBND, @, INLINE.
HELP DELLA FUNZIONE FMINUIT<br />
(<strong>di</strong>sponibile anche on<strong>di</strong>ne dentro a Matlab)<br />
FMINUIT Multi<strong>di</strong>men<strong>si</strong>onal nonlinear minimization by means of the MINUIT<br />
engine. Usage is <strong>si</strong>milar (but not identical) to that of Matlab Fmins.<br />
For a description of the MINUIT commands, read the MINUIT writeup<br />
or type HELP during the interactive execution of Fminuit.<br />
[BestPars, Errs, Chi2, ErrMatrix] = fminuit(FunName, InitGuess, ...);<br />
minimizes a scalar user function named FunName, u<strong>si</strong>ng InitGuess as initial<br />
values of the variational parameters. Here FunName is a string and<br />
InitGuess a vector.<br />
Dots ... stand for a variable number of optional extra-arguments.<br />
The user function depends on one or two variables: a vector of variational<br />
parameters (same <strong>di</strong>men<strong>si</strong>on as InitGuess) and, optionally, on arbitrary<br />
structure of constant data (any data type except a string), respectively.<br />
Functions of more than 2 variables are not supported.<br />
- Note -<br />
If the user function would need to be passed many matrices of constant<br />
data, such matrices should rather be arranged into a cell array or a struct<br />
(Matlab 5 or later) or a list (Scilab 2.5 or later), and passed as a <strong>si</strong>ngle<br />
argument to the user function.<br />
[BestPars, Errs, Chi2, ErrMatrix] = fminuit(FunName, AuxFunName, InitGuess,<br />
...);<br />
(here AuxFunName is a string) behaves as in the previous case. In ad<strong>di</strong>tion,<br />
an auxiliary function named AuxFunName is called whenever a 'CALL 5'<br />
Minuit command is issued. Such a function is passed the following<br />
argument list:<br />
(BestPars, FunName, ErrMatrix), or<br />
(BestPars, Data, FunName, ErrMatrix) if the argument Data (constant data,<br />
see below) is defined.<br />
Values of BestPars and ErrMatrix are those currently returned by Minuit.<br />
Return arguments of the auxiliary function are ignored.<br />
The interface to AuxFunName is mainly intended for logging, or to draw a<br />
run-time plot during the minimization process.<br />
OPTIONAL ARGUMENTS (following InitGuess, in any order)<br />
Data constant data: any data type supported by Matlab (Scilab),<br />
except a string. If this argument is supplied to Fminuit, it is passed to<br />
the user function FunName as its second argument. In the case of chi-square<br />
fitting, Data usually con<strong>si</strong>sts of a 3-column (or 3-row) matrix of<br />
experimental data: the independent variable, measured values of the<br />
dependent variable, and error bars.<br />
- Note to the case of a scalar Data -<br />
The first occurrence of a scalar argument is interpreted as ConstError<br />
(see below). Therefore, in the case that a scalar Data is required by the<br />
user function to be minimized, ConstError has to be specified as well, and<br />
Data must follow in the argument list.<br />
ConstError a scalar parameter. The value returned by the user function to<br />
Fminuit is internally <strong>di</strong>vided by ConstError^2. In the case of chi-square<br />
fitting, ConstError has the meaning of a uniform error bar as<strong>si</strong>gned to<br />
the experimental points. Default value is ConstError = 1.<br />
'-a' or 'a' option switch. Interactive mode.<br />
If the string constant '-a' or 'a' is supplied, Fminuit prompts for Minuit<br />
commands interactively, until 'EXIT', or 'RETURN' is issued.<br />
This is the default behaviour.
'-b' or 'b' option switch. Batch mode.<br />
If the string constant '-b' or 'b' is supplied, Fminuit runs a sequence of<br />
Minuit commands in batch mode without user control. The command sequence<br />
can be defined by the (...,'-c', MinuitCommands, ...) option, or by<br />
creating a global string variable named 'commands' in the caller workspace<br />
(see below).<br />
The default sequence is 'MINIMIZE; IMPROVE' .<br />
..., '-c', MinuitCommands, .... option switch followed by a string<br />
argument. Flow control.<br />
If the string constant '-c' followed by a string argument MinuitCommands<br />
is passed, Fminuit executes the Minuit commands defined in MinuitCommands<br />
when in batch mode. Defining a global non-empty string variable named<br />
'commands' in the caller workspace controls the program flow in the same<br />
way. The latter feature is kept in Fminuit for backward compatibility,<br />
and might be removed in future releases. Controlling the program flow via<br />
the command line should be preferred.<br />
If both the '-c' option and the global variable commands are present, the<br />
latter is overridden.<br />
Minuit commands are separated by one of the characters: ';', '\', '|',<br />
'/', or '@'; for instance,<br />
fminuit(... ,'-c', 'set par 1 3; fix 1; mini; rel 1; mini', ...)<br />
- Note -<br />
The '-c' option switch implicitly implies '-b' and is always effective;<br />
the global variable commands is only effective when batch mode is<br />
explicitly set via the '-b' (or 'b') option switch.<br />
..., '-n', ParameterNames, ... option switch followed by a string<br />
argument. Parameters Names.<br />
If the string constant '-n' followed by a string argument ParameterNames<br />
is passed, within Minuit, the variational parameters are given the names<br />
specified in ParameterNames, instead of the default values 'par #1',<br />
'par #2', ... . Defining a global non-empty string variable named<br />
'parnames' in the caller workspace controls the parameter names in the<br />
same way (backward compatibility; setting name via the command line should<br />
be preferred).<br />
If both the '-n' option and the global variable parnames are present, the<br />
latter is overridden.<br />
Parameter names are separated by commas or blanks, and must be as many as<br />
the variational parameters. If the number of names does not match the<br />
number of parameters, this option is neglected.<br />
..., '-s', StepBounds, .... option switch followed by a matrix.<br />
Definition of parameter steps and limits.<br />
A string constant '-s' in the argument list, followed by a 2-, 3-, or<br />
4-column matrix, defines new parameter steps and/or parameter limits.<br />
Defining a global non-empty matrix variable named 'stepbounds' in the<br />
caller workspace controls parameter steps and/or limits in the same way<br />
(backward compatibility).<br />
The '-c' switch always overrides the global variable stepbounds.<br />
Format of StepBounds is the following.<br />
Each line is referred to a variational parameter.<br />
The first column contains in<strong>di</strong>ces of the parameters whose steps and/or<br />
limits are to be mo<strong>di</strong>fied.<br />
- If StepBounds is a two- or four-column matrix, the second column<br />
is interpreted as the new steps, i.e. StepBounds(k,2) is the step of<br />
the StepBounds(k,1)-th parameter;<br />
- If StepBounds is a three-column matrix, columns 2 and 3 are interpreted<br />
as upper and lower limits, i.e. the StepBounds(k,1)-th parameter is<br />
constrained between StepBounds(k,2) and StepBounds(k,3).<br />
- If StepBounds is a four-column matrix, columns 2 is interpreted as new<br />
steps, column 3 and 4 as parameter limits.
- Note -<br />
step = 0 means that the parameter is kept fixed;<br />
a negative step <strong>si</strong>gnifies usage of the default step definition.<br />
RETURN VALUES<br />
BestPars vector (same <strong>si</strong>ze as InitGuess): the optimized parameters<br />
return by Fminuit.<br />
Errs vector (same <strong>si</strong>ze as InitGuess): the linearized (parabolic)<br />
errors associated to the optimized parameters BestPars.<br />
Chi2 scalar: value of the user function for the variational<br />
parameters BestPars, <strong>di</strong>vided by ConstError^2. Usually, this is the<br />
chi-square value correspon<strong>di</strong>ng to the fitting parameters returned by Fminuit<br />
and the experimental data.<br />
ErrMatrix the error matrix, proportional to the inverse Hes<strong>si</strong>an matrix.<br />
ErrMatrix is a (length(BestPars), length(BestPars)) matrix, correspon<strong>di</strong>ng<br />
row-by-row, column-by-column to the best fit parameters.<br />
Fixed parameters correspond to rows and column padded with zeros.<br />
UNSUPPORTED<br />
Nonlinear errors be can calculated by issuing a MINOS Minuit commands.<br />
Their values however are not interfaced to Matlab (Scilab).<br />
Copyright (C) G. Allo<strong>di</strong> 1996 - 2002