-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_parents.m
41 lines (35 loc) · 1.9 KB
/
get_parents.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function [mothers, fathers] = get_parents(num_children, current_gen, gen_fitness_enum, gen_config_occurrences)
% Selects the parents for a generation based on fitness.
% Probabilities are randomly generated from 0 to 1, and each
% probability is matched to the nearest gen_fitness value without going
% over. Outputs are generated by mapping those gen_fitness_values to
% the original configs.
% Create random probabilities for each child
mother_probs = rand(num_children, 1);
father_probs = rand(num_children, 1);
% Compare the probabilities to fitness, and select the config with the
% nearest fitness value without going over.
fitness_repmat = repmat(gen_fitness_enum(:,2), [1 num_children]);
mother_probs_diff = fitness_repmat - mother_probs';
mother_probs_diff(mother_probs_diff<0) = nan;
[~, mother_idxs] = min(mother_probs_diff);
mother_config_nums = gen_fitness_enum(mother_idxs, 1);
% Repeat process for second parent
father_probs_diff = fitness_repmat - father_probs';
father_probs_diff(father_probs_diff<0) = nan;
[~, father_idxs] = min(father_probs_diff);
father_config_nums = gen_fitness_enum(father_idxs, 1);
% To help preserve population diversity, prevent the mother and father
% from being the same config. If this does occur, change the father to
% the next fittest individual.
for j = 1:num_children
if all(ismember([mother_config_nums(j);father_config_nums(j)], gen_config_occurrences{j}))
nonincest_nums = find(~ismember(1:length(gen_fitness_enum), gen_config_occurrences{j}));
[~,replacement_idx] = min(abs(nonincest_nums-father_config_nums(j)));
father_config_nums(j) = nonincest_nums(replacement_idx(end));
end
end
% Map selected indices to the original configs
mothers = current_gen(:,:,mother_config_nums);
fathers = current_gen(:,:,father_config_nums);
end