• Non ci sono risultati.

in MATLAB, parte 1 & 2

N/A
N/A
Protected

Academic year: 2021

Condividi "in MATLAB, parte 1 & 2"

Copied!
49
0
0

Testo completo

(1)

Metodi di ottimizzazione in MATLAB, parte 1 & 2

KATARZYNA BIZON, POLITECNICO DI CRACOVIA KATARZYNA.BIZON@PK.EDU.PL

(2)

Strumenti di ottimizzazione in Matlab

Funzioni di base:

polyfit polynomial curve fitting

fminbnd find minimum of single-variable function on fixed interval fminsearch find minimum of unconstrained multivariable function using

derivative-free method

lsqnonneg solve nonnegative linear least-squares problem

Toolbox:

Curve Fitting Toolbox Optimization Toolbox

Global Optimization Toolbox

(3)

polyfit & il metodo di minimi quadrati

Supponiamo di disporre di un insieme di dati {(xi,yi), i = 0,…,n}, Cerchiamo un polinomio f di grado m (in genere m<<n) approssima l’insieme di dati nel senso di minimi quadrati.

Il problema si può formulare come segue:

dove

e i coefficienti a0, …, am sono incognite.

0 1

min ( , ,...,

m

)

ai

a a a

( )

2

0 1 0 1

0

( , ,..., ) ...

n m

m i i m i

i

a a a y a a x a x

=

 

 =   − + + + 

(4)

polyfit & il metodo di minimi quadrati

p = polyfit(x,y,n) returns the coefficients for a

polynomial p(x) of degree n that is a best fit (in a least-squares sense) for the data in y. The

coefficients in p are in descending powers, and the length of p is n+1.

Esempio 1: Presents the enthalpy of saturated

steam versus temperature. Determine a 2nd-order polynomial that fits this enthalpy data, and

estimate the enthalpy at T = 373.15 K using the polynomial.

(5)

polyfit & il metodo di minimi quadrati

T = [283.15 303.15 323.15 363.15 393.15 413.15];

H = [2519.9 2556.4 2592.2 2660.1 2706.0 2733.1];

p = polyfit(T, H, 2)

Tv = 280:0.1:415; Hv = polyval(p,Tv);

plot(Tv,Hv,T,H,'o')

xlabel('T(K)'), ylabel('H(kJ/kg)') f = polyval(p, 350.15)

(6)

Minimi quadrati – le alternative in Matlab

Basic Fitting Tool (figure/tools/basic fitting)

(7)

Minimi quadrati – le alternative in Matlab

Curve Fitting Toolbox (commando: cftool)

(8)

Funzioni fminbnd & fminsearch

fminbnd find minimum of single-variable function on fixed interval

fminsearch find minimum of unconstrained multivariable function using derivative-free method

Il problema di ottimizzazione nonlineare posto nella forma:

f*=min {f(x)}

è equivalente al problema:

f*=-max {-f(x)}

f(x)

-f(x)

(9)

Funzione fminbnd

Il comando fminbd trova il minimo di una funzione di una sola variabile indicata con x. La sintassi è: fminbnd(‘funzione’,x1,x2) dove funzione è una stringa che contiene il nome della funzione. Il comando fminbnd restituisce un valore x che rende minima la funzione nell’intervallo x1≤x≤x2.

Per esempio:

fminbnd(‘cos’,0,4)

Per una funzione definita dall’utente definita nel file esterno:

function y=f2(x) y=1-x.*exp(-x);

Per trovare il valore minimo nell’intervallo 0≤x≤5:

x=fminbnd(‘f2’,0,5)

(10)

Funzione fminbnd

Il formato sintattico alternativo restituisce direttamente il valore della funzione per la soluzione x: [x,fval]=fminbnd(‘funzione’,x1,x2)

Invece il comando: [x,fval,exitflag]=fminbnd(‘funzione’,x1,x2) restituisce un valore di exitflag che descrive la condizione di uscita di fminbnd. Il valore exitflag=1 indica che la funzione converge a una soluzione x. Un valore diverso da 1 indica che la funzione non converge a una soluzione.

Per trovare il valore massimo di una funzione si utilizza il comando fminbnd con il segno meno davanti alla funzione. Ad esempio, per trovare il massimo della

funzione y=xe-x 0≤x≤5:

function y=f3(x) y=-x.*exp(-x);

fminbnd(‘f3’,0,5)

(11)

Funzione fminbnd

Esempio 2: A metallic ball released from a height h at an angle θ and velocity v with respect to the horizontal in a gravitational field g travels a distance d when it hits the ground. The distance d is given by:

Use fminbnd function to find θ for which the distance d is a maximum and to determine the maximum distance d.

Data: h = 60 m, v = 80m, g = 9.8 m/sec2, n = 30, a = 0, b = 1.6.

(12)

Funzioni fminbnd & fminsearch

clear all

h = 60; v = 80; g = 9.8; n = 30; a = 0; b =1.6;

d=@(theta) -

(v*sin(theta)/g+sqrt(2*h/g+(v*sin(theta)/g)^2))*v*cos(theta);

[theta1,fval1]=fminbnd(d,0,pi);

rad2deg(theta1) d1=-fval1

[theta2,fval2]=fminsearch(d,0);

rad2deg(theta2) d2=-fval2

(13)

Accoppiamento di fminbnd/fminsearch con altre funzioni di Matlab

Esempio 3: Dynamic parameter estimation Caso 1:

Caso 2:

2 A

A

k

B

dCA

d kC t

⎯⎯ →

− =

A

A B

n k

dCA

d kC t

⎯⎯ →

− =

(14)

Dynamic parameter estimation

clear all

global t1 ke Ce C0

k=1; C0=1;

dC=@(t,C) -k*C^2;

tspan=[0:0.1:15];

[t,Csol]=ode45(dC,tspan,C0);

plot(t,Csol); hold on

% "dati sperimentali"

t1=t(1:10:end); C1=Csol(1:10:end);

C2=Csol(1:10:end)+0.1*(rand(numel(C1),1)-0.5);

plot(t1,C1,'o',t1,C2,'*')

(15)

Dynamic parameter estimation

k0=1.5;

Ce=C1;

[k_estimate1]=fminsearch(@odefit,k0) Ce=C2;

[k_estimate2]=fminsearch(@odefit,k0)

function err=odefit(par) global t1 ke Ce C0

ke=par;

dC=@(t,C) -ke*C^2;

[t1,C]=ode45(dC,t1,C0);

err=sum((C-Ce).^2);

end

2 A

A

k

B

dCA

d kC t

⎯⎯ →

− =

(16)

Dynamic parameter estimation

k0=1.5; n0=3; Ce=C2;

[par_estimate]=fminsearch(@odefit2,[k0 n0])

function err=odefit2(par2) global t1 ke ne Ce C0

ke=par2(1); ne=par2(1);

dC=@(t,C) -ke*C^ne;

[t1,C]=ode45(dC,t1,C0);

err=sum((C-Ce).^2);

end

A

A B

n k

dCA

d kC t

⎯⎯ →

− =

(17)

Determinazione di parametri di modelli complessi

Ottimizzazione della structura di particella ibrida di catalizzatore

(18)

Determinazione di parametri di modelli complessi

Ottimizzazione della structura di particella ibrida di catalizzatore

Il processo chimico:

Funzione obiettivo:

Per calcolare il valore di funzione obiettivo bisogna risolvere 501x4 (nel gas) + 501x51x4 (particella) equazioni!!!

1 2

1 2

A kk B kk C

⎯→ ⎯⎯

1

C,

CA, 1 2 1

A,

max r out subject to 0 1 and 1

f in

Y n f f f

= n   = −

1

C,

CA, 1 2 1

A,

max r out subject to 0 1 and 1

f in

Y n f f f

= n = −

(19)

Funzione fmincon di Optimization Toolbox

fmincon nonlinear programming solver, find minimum of constrained nonlinear multivariable function

(20)

Funzione fmincon - la sintassi

x = fmincon(fun,x0,A,b) starts at x0 and attempts to find a minimizer x of the function described in fun subject to the linear inequalities A*x ≤ b. x0 can be a scalar, vector, or matrix.

x = fmincon(fun,x0,A,b, Aeq,beq) minimizes fun subject to the linear equalities Aeq*x = beq and A*x ≤ b. If no inequalities exist, set A = []

and b = [].

x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub) defines a set of lower and upper bounds on the design variables in x, so that the solution is

always in the range lb ≤ x ≤ ub. If no equalities exist, set Aeq = [] and beq = [].

x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon) subjects the

minimization to the nonlinear inequalities c(x) or equalities ceq(x) defined in nonlcon. fmincon optimizes such that c(x) ≤ 0 and

ceq(x) = 0. If no bounds exist, set lb = [] and/or ub = [].

(21)

Funzione fmincon

clear all

z =@(x) 3*(1-x(1)).^2.*exp(-(x(1).^2) - (x(2)+1).^2) ...

- 10*(x(1)/5 - x(1).^3 - x(2).^5).*exp(-x(1).^2-x(2).^2) ...

- 1/3*exp(-(x(1)+1).^2 - x(2).^2);

peaks

x0 = [0 0];

lb = [-1 -2];

ub = [1 0];

x = fmincon(z,x0,[],[],[],[],lb,ub)

(22)

Prossima lezione

Global Optimization Toolbox:

Provides functions that search for global solutions to problems that contain multiple maxima or

minima. The toolbox includes global search, multistart, pattern search, genetic algorithm,

multiobjective genetic algorithm, simulated annealing, and particle swarm solvers.

(23)

Ottimizzazione di un CSTR

Esempio 4: Ottimizzazione din un CSTR con due reazioni in serie:

( )

( )

( )

1 2

A, A 1 A

B, B 1 A 2 B

C, C 2 B

A C

0 1 0 1

B

0 1

k k

in

in

in

C C k C

C C k C k C

C C k C

⎯⎯→ ⎯⎯→

= − −

= − + −

= − +

(24)

Ottimizzazione di un CSTR

Esempio 4: Ottimizzazione din un CSTR con due reazioni in serie:

Caso 1: massimizare la concentrazione di prodotto B attraverso la scelta di ottimo tempo di residenza

Caso 2: massimizare la concentrazione di prodotto B attraverso la scelta di ottimo tempo di residenza,

mantendeno la concentrazione di C sotto un certo valore

(25)

Ottimizzazione di un CSTR

(26)

Ottimizzazione di un CSTR

clearglobalallCAin k1 k2 tau Climit

CAin=1; k1=1; k2=0.2; Climit=0.05;

tau0=1;

[tau1,fval1]=fminsearch(@fobj,tau0);

function f_obj=fobj(par) global tau

tau=par;

y0=[0.33 0.33 0.33];

yS=fsolve(@cstr_fun,y0);

f_obj=-yS(2);

end

function f=cstr_fun(y) global CAin k1 k2 tau

f(1)=1/tau*(CAin-y(1))-k1*y(1);

f(2)=1/tau*(-y(2))+k1*y(1)-k2*y(2);

f(3)=1/tau*(-y(3))+k2*y(2);

end

(27)

Ottimizzazione di un CSTR

clearglobalallCAin k1 k2 tau Climit

CAin=1; k1=1; k2=0.2; Climit=0.05;

tau0=1;

[tau1,fval1]=fminsearch(@fobj,tau0);

function f_obj=fobj(par) global tau

tau=par;

y0=[0.33 0.33 0.33];

yS=fsolve(@cstr_fun,y0);

f_obj=-yS(2);

end

function f=cstr_fun(y) global CAin k1 k2 tau

f(1)=1/tau*(CAin-y(1))-k1*y(1);

f(2)=1/tau*(-y(2))+k1*y(1)-k2*y(2);

f(3)=1/tau*(-y(3))+k2*y(2);

end

(28)

Funzione fmincon - la sintassi

x = fmincon(fun,x0,A,b) starts at x0 and attempts to find a minimizer x of the function described in fun subject to the linear inequalities A*x ≤ b. x0 can be a scalar, vector, or matrix.

x = fmincon(fun,x0,A,b, Aeq,beq) minimizes fun subject to the linear equalities Aeq*x = beq and A*x ≤ b. If no inequalities exist, set A = []

and b = [].

x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub) defines a set of lower and upper bounds on the design variables in x, so that the solution is

always in the range lb ≤ x ≤ ub. If no equalities exist, set Aeq = [] and beq = [].

x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon) subjects the

minimization to the nonlinear inequalities c(x) or equalities ceq(x) defined in nonlcon. fmincon optimizes such that c(x) ≤ 0 and

ceq(x) = 0. If no bounds exist, set lb = [] and/or ub = [].

(29)

Vincoli nonlineari

(30)

Vincoli nonlineari

Find the point where Rosenbrock's function is minimized within a circle, also subject to bound constraints: the circle centered at [1/3,1/3] with radius 1/3.

fun=@(x) 100*(x(2)-x(1)^2)^2+(1-x(1))^2;

A=[]; b=[]; Aeq=[]; beq=[];

lb=[0,0.2]; ub=[0.5,0.8];

x0=[0.25,0.25];

x=fmincon(fun,x0,A,b,Aeq,beq,lb,ub,@circlecon) function [c,ceq] = circlecon(x)

c=(x(1)-1/3)^2+(x(2)-1/3)^2-(1/3)^2;

ceq=[];

end

(31)

Ottimizzazione di un CSTR

clearglobalallCAin k1 k2 tau Climit

CAin=1; k1=1; k2=0.2; Climit=0.05;

tau0=1;

[tau2,fval2]=fmincon(@fobj,tau0,[],[],[],[],[],[],@

mycon);

function f_obj=fobj(par) ...

end

function [c,ceq]=mycon(par) global tau Climit

tau=par;

y0=[0.33 0.33 0.33];

yS=fsolve(@cstr_fun,y0);

c=yS(3)-Climit;

ceq=[];

end

function f=cstr_fun(y) ...

end

(32)

Funzione fmincon

clear all

z =@(x) 3*(1-x(1)).^2.*exp(-(x(1).^2) - (x(2)+1).^2) ...

- 10*(x(1)/5 - x(1).^3 - x(2).^5).*exp(-x(1).^2-x(2).^2) ...

- 1/3*exp(-(x(1)+1).^2 - x(2).^2);

peaks

x0 = [0 0];

lb = [-1 -2];

ub = [1 0];

x = fmincon(z,x0,[],[],[],[],lb,ub)

(33)

Global Optimization Toolbox

Global Optimization Toolbox:

Provides functions that search for global solutions to problems that contain multiple maxima or

minima. The toolbox includes global search, multistart, pattern search, genetic algorithm,

multiobjective genetic algorithm, simulated annealing, and particle swarm solvers.

(34)

Global Optimization Toolbox

GlobalSearch

and MultiStart have similar approaches to finding global or multiple minima. Both algorithms start a local solver (such as fmincon) from multiple start points. The algorithms use multiple start points to

sample multiple basins of

attraction.

(35)

GlobalSearch

GlobalSearch object contains properties (options) that affect how run

repeatedly runs a local solver to generate a GlobalOptimSolution object.

When run, the solver attempts to locate a solution that has the lowest objective function value.

gs = GlobalSearch creates gs, a GlobalSearch solver with its properties set to the defaults.

problem =

createOptimProblem('solverName','ParameterName',ParameterValue,...) accepts one or more comma-separated parameter name/value pairs.

(36)

Oggetto GlobalSearch

clear all

z =@(x) 3*(1-x(1)).^2.*exp(-(x(1).^2) - (x(2)+1).^2) ...

- 10*(x(1)/5 - x(1).^3 - x(2).^5).*exp(-x(1).^2-x(2).^2) ...

- 1/3*exp(-(x(1)+1).^2 - x(2).^2);

peaks

gs = GlobalSearch;

problem = createOptimProblem('fmincon','x0',[-1,0],...

'objective',z,'lb',[-3,-3],'ub',[3,3]);

X=run(gs,problem)

(37)

Ottimizzazione multiobiettivo

I problemi progettuali nella loro essenza sono sempre di carattere multiobiettivo, tuttavia spesso vengono impostati come i problemi monoobiettivo.

Ottimizzazione di due o di più criteri – o obiettivi – progettuali contrastanti è un oggetto abbastanza recente di ricerche ed il suo significato non è stato ancora completamente esplorato.

Pensando al progetto di un sistema, la procedura tipica comincia con l’attribuire il massimo livello di importanza alla richiesta di una certa prestazione,

considerata come l’aspetto più notevole dello progetto finale. In seguito si

considerano gli obiettivi secondari, che vengono valutati e classificati come non essenziali. Lo svantaggio principale di questa logica è che tutti i criteri di

progetto, per semplicità, vengono ridotti ad un solo obiettivo da ottimizzare, e ad un insieme di vincoli.

(38)

Ottimizzazione multiobiettivo

Formalmente, considerando nv variabili, un problema di ottimizzazione multiobiettivo può essere definito:

soggetto ai nc vincoli di disuguaglianza e ne vincoli di uguaglianza:

e 2nv limiti di diseguaglianza:

dove è un vettore obiettivo composto da nf ≥ 2 termini.

0

( )

dato nv, si cerca inf , nv

x

xF x x

( ) ( )

0, 1, , 0, 1, ,

i c

i e

g x i n

h x i n

=

= =

( ) ( )

0, 1, , 0, 1, ,

i c

i e

g x i n

h x i n

 =

= =

, 1, ,

k k k v

lxu k = n

( ) 

1

( )

, , nf

( ) 

nf

F x = f x f x

(39)

Ottimizzazione multiobiettivo

Tradizionalmente, il problema multiobiettivo viene ridotto al problema

monoobiettivo introducendo la funzione di preferenza , per esempio la somma pesata degli obiettivi:

con che viene minimizzata rispetto a .

Quindi, per un dato insieme di pesi, la soluzione ottenuta viene considerata

ottimale ed è chiaro che la gerarchia attribuita ad uno degli obiettivi può essere modificata cambiando il peso corrispondente

( )

x

( ) ( )

1 nf

i i i

x c f x

=

=

0 i 1, nf1 i 1

c i= c

 

=

nv

x 

nv

x 

(40)

Teoria di Pareto

L’approccio alternativo di ottimizzazione di problemi multiobiettivo è stato introdotto da Pareto. Il concetto del cosiddetto “ottimo paretiano” è

largamente applicato in economia, teoria dei giochi, ingegneria e scienze sociali. Si realizza quando l'allocazione delle risorse è tale che non è possibile apportare miglioramenti paretiani al sistema cioè non si può migliorare la condizione di un soggetto senza peggiorare la condizione di un altro.

Invece, il fronte di Pareto è l’insieme delle soluzioni ottime, cioè il fronte delle soluzioni “non dominate” per cui non è più possibile diminuire il valore della funzione senza simultaneo incremento del valore di almeno una delle altre funzioni obiettivo.

nv

x 

(41)

Teoria di Pareto

Lo spazio obiettivo per il problema con due obiettivi (sinistra) ed i punti di compromesso tra due obiettivi (destra).

Secondo la teoria dell’ottimo paretiano, una

soluzione domina un'altra soluzione se la prima è migliore della seconda rispetto ad uno degli

obiettivi, senza peggiorare alcun altro obiettivo.

Due soluzioni si dicono invece indifferenti se la prima è migliore della seconda rispetto ad un obiettivo mentre la seconda è migliore della prima rispetto a tutti gli altri obiettivi.

nv

x 

(42)

Ottimizzazione multiobiettivo in Maltab

fgoalattain di Optimization Toolbox solve multiobjective goal attainment problems (using weighting).

gamultiobj di Global Optimization Toolbox find Pareto front of multiple fitness functions using genetic algorithm.

(43)

Determinazione di parametri di modelli complessi

Ottimizzazione della structura di particella ibrida di catalizzatore e dell’intera struttura di letto fisso

(44)

Determination of the optimal distribution of active centers in a

multifunctional catalyst pellet using global searching combined with reduced-order modeling approach, Bizon & Continillo, ESCAPE29

The steady-state mass balance equations of a single porous catalyst pellet in which multistep chemical

reactions take place are written

as:

1 2

1

A k B k C

k

⎯⎯→ ⎯⎯→

⎯⎯

( )

( )

2

A A 2 1 A 1 B

1 1 2

1 1

2

2 2

B B 1 A 1 B

1 1 2 2 B

2

1 1

A A

,A A

0 1

B B

,B B

0 1

2 2

0; Bi (1)

0; Bi (1)

bulk

bulk

d d k k

d f k k

d

d d k k

f f

d k k

d

d d

d d

d d

d d

 

= =

= =

+ − 

+

+ +  − 

+

= =

= =

The optimization problem consists in finding the distribution which maximizes the yield of

product C with respect to reactant A which is defined as the ratio between the observed production rate of C and the consumption rate of A evaluated at the bulk gas conditions:

under the constraint resulting from the pellet mass balance and the constraints related to the volume fractions of each functionality and to the constant total amount of each catalyst:

2( ) f

1 2

2 2 B 0

CA

1 1

3 f k d

Y k k

  

=

1 2

2 2

0 f ( ) 1 and 3

0 f ( )   d = where 0   1

(45)

Determination of the optimal distribution of active centers in a

multifunctional catalyst pellet using global searching combined with reduced-order modeling approach, Bizon & Continillo, ESCAPE29

(46)

Determination of the optimal distribution of active centers in a

multifunctional catalyst pellet using global searching combined with reduced-order modeling approach, Bizon & Continillo, ESCAPE29

(47)

Efficient optimization of a multifunctional catalytic fixed-bed reactor via reduced-order modeling approach, Bizon & Continillo, Chemical Engineering Research and Design 2021

1

C,

CA, 1 2 1

A, A,

max r out subject to 0 1 and 1

f in out

Y n f f f

n n

= = −

1

C, CA,

A, A,

1 2 1

max

subject to 0 1 and 1

out f r

in out

Y n

n n

f f f

= −

  = −

The objective function to be

maximized is defined as:

(48)

Efficient optimization of a multifunctional catalytic fixed-bed reactor via reduced-order modeling approach, Bizon & Continillo, Chemical Engineering Research and Design 2021

Number of layers, Rz

FOM

f1 YCA,r

1 0.440326 0.898108 2 0.574192

0.000004 0.947115

3

0.760692 0.000015 0.000003

0.953902

1

(base case) 0.5 0.895276

(49)

Applicazioni

Riferimenti

Documenti correlati

Leggere (nella variabile I) e mostrare a video l’immagine rice.png (potrebbe rappresentare un’immagine microscopica, oppure dei pezzi lavorati) Scopo dell’esercizio sarà contare

Genetic Algorithm Particle Swarm Optimization Based Hardware Evolution Strategy.. Zhang Junbin, Cai Jinyan, Meng Yafeng,Meng Tianzhen Department of Electronic and

In some recent works [10-12], The mean value theorem is used to write the state estimation error as a linear system with uncertain parameters.. The use of this theorem provides

Section 5 formulates the mathematical model for the optimal design of a drive shaft; it also explains the objective function and the set of constraints associated with

„ „ allow the formation and maintenance of allow the formation and maintenance of sets of prototypes for each class. sets of prototypes for

As part of the research works, results of which are presented in the paper, OFF-LINE and ON- LINE calibration of water supply network model parameters using two methods was carried

Thus, the research it will be carried out a comparison between genetic algorithm and hill climbing based on the calculation of the shortest path and computing time to see which

 Constrained nonlinear optimization, including goal attainment problems, minimax problems, and semi- infinite minimization problems..  Quadratic and