You are on page 1of 12

APLIKASI SIMULATED ANNEALING

(Tugas Final Test Computational Intensive)

Adi Wijaya
NRP. 1310201720
Program Pascasarjana, Jurusan Komputasi Statistika, Fakultas MIPA, Institut Teknologi Sepuluh Nopember, Surabaya Email: adiw@bps.go.id

Pengantar Simulated Annealing Simulated Annealing adalah suatu algoritma optimasi yang mensimulasikan proses annealing pada pembuatan materi yang terdiri dari butir kristal atau logam.

aplikasinya dalam masalah optimasi dilakukan pertama kali oleh Kirkpatrick et al. tahun 1983. Algoritma ini beranalogi dengan proses annealing (pendinginan) yang diterapkan dalam pembuatan material glassy (terdiri dari butir kristal). Ide dasar simulated annealing berawal dari peristiwa fisika berikut. Apabila

akan dihasilkan kristalkristal dengan kualitas baik. Sebaliknya, jika materi

Persamaan ini merepresentasikan probabilitas suatu new state lebih buruk dari current state masih mungkin terpilih sebagai next state. Berikut adalah persamaan dari probabilitas yang digunakan :

Dalam persamaan tersebut, k merupakan konstanta Boltzman, T adalah temperatur dan r adalah bilangan acak antara 0 dan 1. Sedangkan fungsi biaya direpresentasikan dengan nilai delta energi. Semakin kecil temperatur (T), maka probabilitasnya pun akan semakin kecil. Berbeda dengan temperatur, nilai delta energi yang semakin besar akan membuat probabilitas semakin kecil. Probabilitas yang semakin kecil

ad

SA juga menggunakan persamaan Boltzman dalam sistem termodinamika.

iw

permasalahan optimasi.

ta

Konsep ini yang kemudian diadaptasi oleh SA untuk menyelesaikan beragam

lk

didinginkan terlalu cepat, maka kristal yang dihasilkan pun tidak akan sempurna.

s. w

suatu materi dipanaskan hingga mencair, kemudian didinginkan secara perlahan maka

or dp
1

re

ss

Algoritma SA ini diperkenalkan oleh Metropolis et al. pada tahun 1953, dan

.c

om

menandakan bahwa kemungkinan terpilihnya suatu new state dengan biaya yang lebih besar dari current state akan semakin kecil. Berikut ini adalah pemetaan dari Physical Annealing ke Simulated Annealing : Berikut ini adalah pemetaan dari Physical Annealing ke Simulated Annealing :

Fisika (termodinamika) Keadaan sistem Energi Perubahan keadaan Temperatur Keadaan beku

Simulated Annealing Solusi yang mungkin Biaya Solusi tetangga Parameter kontrol Solusi heuristik

Hal paling awal dan paling penting adalah menentukan desain solusi yang tepat. Dalam SA, sebuah solusi dikenal dengan istilah State. Suatu state perlu memiliki ukuran apakah baik atau tidaknya state tersebut. Ukuran baik atau tidaknya

beberapa istilah diatas, dalam SA juga dikenal istilah jadwal pendinginan, yaitu kapan suatu temperatur harus diturunkan dan berapa penurunannya. Pada setiap temperatur, SA akan menggunakan sejumlah iterasi untuk mengevaluasi sekumpulan solusi baru.

create initial state set initial temperature Tstart while Tnow > Tend repeat n times generate newState delta energi = (energi baru-energi lama) if delta energi < 0 currentState = newState elseif rand(0,1) < exp(-deltaenergi/T), currentState = newState endif end repeat decrease T end while

Contoh permasalahan yang menggunakan SA sebagai optimasinya: (TUGAS pertama)


Solution to Economic Dispatch by simulated annealing RM Saloman danaraj EEE Department Jubail Industrial Collge, Jubail,Kingdom Of Saudi Arabia.

ad

iw

ta

lk

Untuk lebih detailnya, berikut adalah algoritma SA.

s. w

or dp
2

maka energi akhir haruslah lebih kecil dibandingkan dengan energi awal. Selain

re

state tersebut dinyatakan dengan energi. Karena SA dirancang untuk kasus minimasi,

ss

.c

om

Masalah muatan secara ekonomis sering terkait dengan pengalokasian muatan untuk mesin-mesin industri dalam perolehan biaya yang minimum ketika bertemu dengan. Hal ini berarti diformulasikan sebagai sebuah permasalahan optimisasi dalam minimalisasi jumlah biaya bahan bakar dari mesin industri yang dimasukkan saat berpotongan atau bersinggungan dengan permintaan dan kehilangan. Variasi dari masalah tersebut cukup besar terkait dengan model dengan tujuan dan batasan yang berbeda-beda. Penyelesaian masalah secara ekonomis dapat dideskripsikan secara matematis sebagai sebuah minimalisasi masalah dari pengurangan jumlah biaya bahan bakar dari semua mesin-mesin yang memiliki keterbatasan.
n Minimize F ( Pi ) i 1 i

Fij ( Pi ) ai Pi bi Pi ci , Pi
2

or dp
min

kuadratik.

re
n n i 1 j 1

bangkitan (MW). Secara normal, fungsi tersebut digambarkan sebagai fungsi


Pi Pi

Jumlah bangkitan seharusnya berpotongan dengan jumlah permintaan dan kehilangan transmisi yang dapat ditetapkan dari koefisien Bmn maupun aliran kekuatan.

s. w
n i 1

lk

P
m i

D Pl
n j

ta

Solusi dengan menggunakan SA 1. Pilih sebuah mesin sebagai rujukan. Agar menghasilkan ke-konvergen-an yang lebih baik, pilih lah mesin yang memiliki kapasitas dan jarak maksimum. Pada program ini, mesin tersebut disebut sebagai mesin 1. Alokasi dari mesin rujukan tersebut ditetapkan dengan kedua persamaan di atas 2. Ubah masalah optimasi yang sudah dibatasi sebagai sebuah masalah yang belum berbatas dengan menggunakan metode fungsi penalty (akhir)
Minimize

ad

iw

Pl Bij Pi Pj

F ( P ) 1000 * abs( P D B P P )
i 1 i i i 1 i ij i j

ss
max

merupakan variasi dari biaya bahan bakar (dalam US$ atau Rs) dengan kekuatan

.c

Dimana, Fi ( Pi ) adalah fungsi biaya bahan bakar pada mesin ke-i yang juga

om

3. This software contain one example By running the program test1.m as it is in the default folder the economic dispatch problem is solved. The allocation minimum fuel cost and transmission losses can be determined. 3. Pada rangkaian syntax (3 syntax code) mengandung sebuah contoh dengan melakukan running file test1.m. Data default sudah dimasukkan kedalam syntax tersebut dan alokasi biaya bahan bakar dan kehilangan transmisi minimum dapat ditetapkan. Berikut hasil run syntax test1 yang diambil dari buku Power System Analysis oleh Prof. Haadi Sadaat Example 7.8
The results T = 100.00000, loss = 275959.66149 T = 80.00000, loss = 213371.74104 T = 0.00030, loss = 36912.20569 T = 0.00024, loss = 36912.20575 T = 0.00019, loss = 36912.20473 T = 0.00000, loss = 36912.20392 T = 0.00000, loss = 36912.20392 Initial temperature: Final temperature: Consecutive rejections: Total final loss: F =

lk

Number of function calls:

3.6912e+004

P1 = 28.2942 10.0001 118.9561 118.6795 230.7623 212.7395

Pl = 19.4317 Elapsed time is 86.151590 seconds.

Interpretasi hasil running:


4

ad

iw

ta

s. w

or dp
100 9.04626e-007 13114 250815 36912.2

re

ss

.c

om

Dapat diperoleh keputusan bahwa alokasi biaya bahan bakar dan kehilangan transmisi yang minimum untuk ke masing-masing mesin adalah sebagai berikut: Mesin ke1 2 3 4 5 6 Biaya alokasi (US$) 28.2942 10.0001 118.9561 118.6795 230.7623 212.7395

dialokasikan ke semua mesin adalah 19.4317

Syntax code Simulated Annealing (SA) nya

function [minimum,fval] = anneal(loss, parent, options) % ANNEAL Minimizes a function with the method of simulated annealing % (Kirkpatrick et al., 1983) % % ANNEAL takes three input parameters, in this order: % % LOSS is a function handle (anonymous function or inline) with a loss % function, which may be of any type, and needn't be continuous. It does, % however, need to return a single value. % % PARENT is a vector with initial guess parameters. You must input an % initial guess. % % OPTIONS is a structure with settings for the simulated annealing. If no % OPTIONS structure is provided, ANNEAL uses a default structure. OPTIONS % can contain any or all of the following fields (missing fields are % filled with default values): % % Verbosity: Controls output to the screen. % 0 suppresses all output % 1 gives final report only [default] % 2 gives temperature changes and final report % Generator: Generates a new solution from an old one. % Any function handle that takes a solution as input and % gives a valid solution (i.e. some point in the solution % space) as output. % The default function generates a row vector which % slightly differs from the input vector in one element: % @(x) (x+(randperm(length(x))==length(x))*randn/100) % Other examples of possible solution generators: % @(x) (rand(3,1)): Picks a random point in the unit cube % @(x) (ceil([9 5].*rand(2,1))): Picks a point in a 9-by-5 % discrete grid % Note that if you use the default generator, ANNEAL only % works on row vectors. For loss functions that operate on % column vectors, use this generator instead of the % default: % @(x) (x(:)'+(randperm(length(x))==length(x))*randn/100)' % InitTemp: The initial temperature, can be any positive number. % Default is 1. % StopTemp: Temperature at which to stop, can be any positive number % smaller than InitTemp. % Default is 1e-8. % StopVal: Value at which to stop immediately, can be any output of

ad

iw

ta

lk

s. w

or dp
5

re

ss

.c

om

Sedangkan biaya bahan bakar dan kehilangan transmisi optimum yang dapat

def = struct(... 'CoolSched',@(T) (.8*T),... 'Generator',@(x) (x+(randperm(length(x))==length(x))*randn/100),... 'InitTemp',100,... 'MaxConsRej',10000,... 'MaxSuccess',50,... 'MaxTries',10000,... 'StopTemp',1e-10,... 'StopVal',-Inf,... 'Verbosity',2); % Check input if ~nargin %user wants default options, give it and stop minimum = def; return elseif nargin<2, %user gave only objective function, throw error error('MATLAB:anneal:noParent','You need to input a first guess.'); elseif nargin<3, %user gave no options structure, use default options=def; else %user gave all input, check if options structure is complete if ~isstruct(options) error('MATLAB:anneal:badOptions',...

ad

% %

joachim.vandekerckhove@psy.kuleuven.be $Revision: v5 $ $Date: 2006/04/26 12:54:04 $

iw

% % %

Reference: Kirkpatrick, S., Gelatt, C.D., & Vecchi, M.P. (1983). Optimization by Simulated Annealing. _Science, 220_, 671-680.

ta

lk

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

CoolSched:

MaxConsRej: MaxTries: MaxSuccess:

LOSS that is sufficiently low for you. Default is -Inf. Generates a new temperature from the previous one. Any function handle that takes a scalar as input and returns a smaller but positive scalar as output. Default is @(T) (.8*T) Maximum number of consecutive rejections, can be any positive number. Default is 1000. Maximum number of tries within one temperature, can be any positive number. Default is 300. Maximum number of successes within one temperature, can be any positive number. Default is 20.

Example: The so-called "six-hump camelback" function has several local minima in the range -3<=x<=3 and -2<=y<=2. It has two global minima, namely f(-0.0898,0.7126) = f(0.0898,-0.7126) = -1.0316. We can define and minimise it as follows: camel = @(x,y)(4-2.1*x.^2+x.^4/3).*x.^2+x.*y+4*(y.^2-1).*y.^2; loss = @(p)camel(p(1),p(2)); [x f] = ANNEAL(loss,[0 0]) We get output: Initial temperature: 1 Final temperature: 3.21388e-007 Consecutive rejections: 1027 Number of function calls: 6220 Total final loss: -1.03163 x = -0.0899 0.7127 f = -1.0316 Which reasonably approximates the analytical global minimum (note that due to randomness, your results will likely not be exactly the same).

s. w

or dp
6

re

ss

.c

om

Usage: [MINIMUM,FVAL] = ANNEAL(LOSS,NEWSOL,[OPTIONS]); MINIMUM is the solution which generated the smallest encountered value when input into LOSS. FVAL is the value of the LOSS function evaluated at MINIMUM. OPTIONS = ANNEAL(); OPTIONS is the default options structure.

'Input argument ''options'' is not a structure') end fs = {'CoolSched','Generator','InitTemp','MaxConsRej',... 'MaxSuccess','MaxTries','StopTemp','StopVal','Verbosity'}; for nm=1:length(fs) if ~isfield(options,fs{nm}), options.(fs{nm}) = def.(fs{nm}); end end end % main settings newsol = options.Generator; % neighborhood space function Tinit = options.InitTemp; % initial temp minT = options.StopTemp; % stopping temp cool = options.CoolSched; % annealing schedule minF = options.StopVal; max_consec_rejections = options.MaxConsRej; max_try = options.MaxTries; max_success = options.MaxSuccess; report = options.Verbosity; k = 1; % boltzmann constant % counters etc itry = 0; success = 0; finished = 0; consec = 0; T = Tinit; initenergy = loss(parent); oldenergy = initenergy; total = 0; if report==2, fprintf(1,'\n

newparam = newsol(current); newenergy = loss(newparam); if (newenergy < minF), parent = newparam; oldenergy = newenergy; break end if (oldenergy-newenergy > 1e-6) parent = newparam; oldenergy = newenergy; success = success+1; consec = 0; else if (rand < exp( (oldenergy-newenergy)/(k*T) )); parent = newparam; oldenergy = newenergy; success = success+1; else consec = consec+1; end end end

ad

iw

% % Stop / decrement T criteria if itry >= max_try || success >= max_success; if T < minT || consec >= max_consec_rejections; finished = 1; total = total + itry; break; else T = cool(T); % decrease T according to cooling schedule if report==2, % output fprintf(1,' T = %7.5f, loss = %10.5f\n',T,oldenergy); end total = total + itry; itry = 1; success = 1; end end

ta

lk

s. w

or dp
7

re

while ~finished; itry = itry+1; % just an iteration counter current = parent;

ss

T = %7.5f, loss = %10.5f\n',T,oldenergy); end

.c

om

minimum = parent; fval = oldenergy; if report; fprintf(1, fprintf(1, fprintf(1, fprintf(1, fprintf(1, end '\n Initial temperature: \t%g\n', Tinit); ' Final temperature: \t%g\n', T); ' Consecutive rejections: \t%i\n', consec); ' Number of function calls:\t%i\n', total); ' Total final loss: \t%g\n', fval);

Fungsi yang akan diminimumkan % This program solves the economic dispatch with Bmn coefficients by % Genetic Algorithm % the data matrix should have 5 columns of fuel cost coefficients and plant limits. % 1.a ($/MW^2) 2. b $/MW 3. c ($) 4.lower limit(MW) 5.Upper limit(MW) %no of rows denote the no of plants(n) % x=[0 0] function [ F P1 Pl]=saeld(x) global data B Pd x=abs(x); n=length(data(:,1)); for i=1:n-1 if x(i)>1; x(i)=1; else end P(i)=data(i+1,4)+x(i)*(data(i+1,5)-data(i+1,4)); end B11=B(1,1); B1n=B(1,2:n); Bnn=B(2:n,2:n); A=B11; BB1=2*B1n*P'; B1=BB1-1; C1=P*Bnn*P'; C=Pd-sum(P)+C1; x1=roots([A B1 C]); % x=.5*(-B1-sqrt(B1^2-4*A*C))/A x=abs(min(x1)); if x>data(1,5) x=data(1,5); else end if x<data(1,4) x=data(1,4); else end P1=[x P]; for i=1:n F1(i)=data(i,1)* P1(i)^2+data(i,2)*P1(i)+data(i,3); end Pl=P1*B*P1'; lam=abs(sum(P1)-Pd-P1*B*P1'); F=sum(F1)+1000*lam; Cara menjalankan SA dengan menggunakan data dari mesin rujukan clear; clc; % This program solves the economic dispatch with Bmn coefficients by % simulated annealing.For any % discussion&Clarification the author can be contacted by mail (salorajan@gmail.com) % The Example system is taken from the book Power System Analysis by Prof Haadi Sadaat Example % 7.8 % the data matrix should have 5 columns of fuel cost coefficients and plant limits. % 1.a ($/MW^2) 2. b $/MW 3. c ($) 4.lower limit(MW) 5.Upper limit(MW) %no of rows denote the no of plants(n) % x=[0 0] clear; clc;

ad

iw

ta

lk

s. w

or dp
8

re

ss

.c

om

tic; global data B Pd % This program solves the economic dispatch with Bmn coefficients byGenetic % The data matrix should have 5 columns of fuel cost coefficients and plant limits. % 1.a ($/MW^2) 2. b $/MW 3. c ($) 4.lower lomit(MW) 5.Upper limit(MW) %no of rows denote the no of plants(n) data=[0.15247 38.53973 756.79886 10 125 0.10587 46.15916 451.32513 10 150 0.02803 40.3965 1049.9977 35 225 0.03546 38.30553 1243.5311 35 210 0.02111 36.32782 1658.569 130 325 0.01799 38.27041 1356.6592 125 315]; B=1e4*[1.4 .17 .15 .19 .26 .22;.17 .60 .13 .16 .15 .20;.15 .13 .65 .17 .24 .19;. 19 .16 .17 .71 .30 .25;.26 .15 .24 .30 .69 .32;.22 .20 .19 .25 .32 .85]; Pd=700; n=length(data(:,1)); p1=zeros(1,n-1); [minimum,fval] = anneal(@saeld, p1) ; [ F P1 Pl]=saeld(minimum) toc;

CONTOH APLIKASI TOOLBOX MATLAB modifikasi data input dari koordinat menjadi jarak

Proses yang dilakukan sederhana, yaitu dengan mengubah input dalam matriks koordinat menjadi jarak yang antara satu matrik (x) dengan matrik lainnya memiliki nilai yang sama dan melakukan modifikasi terhadap file anneal_reverse.m. m-file ini perlu dilakukan modfikasi dengan menonaktifkan (menghapus) length path yang tersimpan di file alen.m. Sehingga output yang dihasilkan dari proses running file order.m hanya menampilkan urutan optimum iorder atau lokasi (kota) seiring turunnya temperature. Data input yang digunakan merupakan data jarak antar beberapa kota di Jawa dalam kilometer (km) yaitu sbb disimpan dalam workspace x dan y: Tabel 1 Jarak antar kota/kabupaten di Jawa
Kabupaten/kota Madiun Magelang Malang Pekalongan Purworejo 1 2 3 4 5 221 184 315 245 406 138 44 499 429 170 1 2 221 3 184 406 4 315 138 499 5 245 44 429 170 6 222 443 91 508 446 7 145 184 275 210 228 8 214 75 397 101 119 9 788 611 671 473 593 10 677 500 860 362 458 11 169 370 89 409 393

ad

iw

ta

lk

s. w

or dp
9

(TUGAS kedua)

re

ss

.c

om

Probolinggo Rembang Semarang Serang Sukabumi Surabaya

6 7 8 9 10 11

222 145 214 788 677 169

443 184 75 611 500 370

91 275 397 971 860 89

508 210 101 473 362 409

445 228 119 593 458 393 300 407 981 870 99

300

407 109

981 683 574

870 572 463 203

99 201 308 882 771

109 683 572 201 574 463 308

203 882 771

Modifikasi syntax pada file anneal_reverse.m


function anneal_reverse(x,y,ncity) % % anneal_reverse(x,y,ncity) % global iorder;

%fprintf(1,'Initial Path Length = %12.6f \n',path) for j=1:100 nsucc=0; for k=1:nover nn=0; while nn<3 n(1)=1+floor(ncity*rand(1)); n(2)=1+floor((ncity-1)*rand(1)); if n(2) >= n(1) n(2)=n(2)+1; end nn=1+mod((n(1)-n(2)+ncity-1),ncity); end

ad

de=revcst(x,y,ncity,n); ans=metrop(de,t); if ans nsucc=nsucc + 1; %path = path + de; reverse(ncity,n);

iw

ta

lk

tfactor=0.9; %tfactor=0.01; nover=100*ncity; nlimit=10*ncity; %path=0 t=0.5; %code ini lah yang dihapus (dimodifikasi) %for i=1:ncity-1 % i1=iorder(i); % i2=iorder(i+1); % path = path + alen(x(i1),x(i2),y(i1),y(i2)) %end %i1=iorder(ncity); %i2=iorder(1); %path = path + alen(x(i1),x(i2),y(i1),y(i2))

s. w

or dp
10

re

ss

.c

om

end if nsucc >= nlimit break; end end %fprintf(1,'T = %10.6f,%Path Length = %12.6f \n',t,path); fprintf(1,'Successful Moves: %6d\n',nsucc); iorder % display current iorder t=t*tfactor; if nsucc == 0 return; end end

Pemanggilan syntax untuk proses running dengan order.m


global iorder x; y; iorder=[11,3,1,5,7,9,4,6,8,2,10]; %tentukan sendiri untuk langkah awal ncity=length(iorder); anneal_reverse(x,y,ncity);

Successful Moves:

110

11

ad

iorder =

iw

ta

Output yang dihasilkan dari proses tersebut adalah:

lk

10

Successful Moves: iorder = 6 2 8 3

110

11 110

Successful Moves: iorder = 6 1 7 11

3 110

Successful Moves: iorder = 3 8 6 4

10

s. w
4 5 6 2 4 9 10 5 5 9 10 4 2 7 1 11

or dp
11

re

ss

.c

om

Successful Moves:

110

iorder =

10

11

Analisis: dapat diketahui bahwa rute yang optimum atau efektif adalah sbb: 3 8 6 5 10 9 4 2 7 1 11

Malang Semarang Probolinggo Purworejo Sukabumi Serang Pekalongan Magelang Rembang Madiun Surabaya

ad

iw

ta

lk

s. w
12

or dp

re

ss

.c

om

You might also like