Commit e6ef8151 authored by Oiwi's avatar Oiwi
Browse files

Initial commit (3rd version, new particles each cycle)

parents
function best = particle_filter( objective_fun, range, variance, Nparticles, Nkeep, Nnew, Ncycles )
%
% objective_fun
% Function handle which, given a particle, returns a positive score to be maximised.
%
% range
% A Ndim x 2 array in which each row specifies the min/max value in each dimension.
%
% Nparticles
% Some large integer.
%
% Nkeep
% Number of particles serving as seeds during resampling.
%
% Nnew
% Number of new particles to generate at each cycle.
%
% Ncycles
% Number of cycles to run.
assert( Nkeep < Nparticles );
assert( Nnew < Nparticles );
% initialise the particles
particles = initialise( range, Nparticles );
scores = evaluate( objective_fun, particles );
% initialise output
[best_score,best] = max(scores);
best = particles(:,best);
for c = 1:Ncycles
% resample
keep = importance_sampling( scores, Nkeep );
particles = [ resample( particles(:,keep), variance, Nparticles-Nnew ), initialise(range,Nnew) ];
% evaluate
scores = evaluate( objective_fun, particles );
% update best particle
[~,best_index] = max(scores);
if scores(best_index) > best_score
best_score = scores(best_index);
best = particles(:,best_index);
end
end
end
function particles = initialise( range, n )
Vmin = range(:,1);
Vmax = range(:,2);
Ndims = size(range,1);
particles = bsxfun( @times, rand(Ndims,n), Vmax-Vmin );
particles = bsxfun( @plus, particles, Vmin );
end
function scores = evaluate( objective_fun, particles )
n = size(particles,2);
scores = zeros(1,n);
for i = 1:n
scores(i) = objective_fun(particles(:,i));
end
end
function particles = importance_sampling( scores, n )
gamma = cumsum(scores);
gamma = [0 gamma] / gamma(end);
particles = rand(1,n);
for i = 1:n
particles(i) = find( particles(i) > gamma, 1, 'last' );
end
end
function particles = resample( seeds, variance, n )
[Ndims,Nseeds] = size(seeds);
particles = seeds(:,randi( Nseeds, 1, n ));
noise = bsxfun( @times, randn(Ndims,n), variance );
particles = bsxfun( @plus, particles, noise );
end
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment