1 /**********************************************************************
2 ga_core.c
3 **********************************************************************
4
5 ga_core - Genetic algorithm routines.
6 Copyright ©2000-2005, Stewart Adcock <stewart@linux-domain.com>
7 All rights reserved.
8
9 The latest version of this program should be available at:
10 http://gaul.sourceforge.net/
11
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version. Alternatively, if your project
16 is incompatible with the GPL, I will probably agree to requests
17 for permission to use the terms of any other license.
18
19 This program is distributed in the hope that it will be useful, but
20 WITHOUT ANY WARRANTY WHATSOEVER.
21
22 A full copy of the GNU General Public License should be in the file
23 "COPYING" provided with this distribution; if not, see:
24 http://www.gnu.org/
25
26 **********************************************************************
27
28 Synopsis: Routines for handling populations and performing GA
29 operations.
30
31 Also contains a number of helper functions providing
32 alternative optimisation schemes for comparison and
33 analysis purposes.
34
35 BEWARE: MANY FUNCTIONS ARE NOT THREAD-SAFE!
36
37 Internally, and in the public C interface, pointers
38 are used to identify the population and entity
39 structures. However, in the scripting interface these
40 pointers are unusable, so identifing integers are
41 used instead.
42
43 Vague usage details: Set-up with ga_genesis_XXX(), where XXX is a built-in chromosome type().
44 Perform calculations with ga_evolution().
45 Grab data for post-analysis with ga_transcend().
46 Evolution will continue if ga_evolution() is
47 called again without calling ga_genesis_XXX() again.
48
49 To do: Replace the send_mask int array with a bit vector.
50 All functions here should be based on entity/population _pointers_ while the functions in ga_intrinsics should be based on _handles_.
51 More "if ( !pop ) die("Null pointer to population structure passed.");" checks are needed.
52 Population/entity iterator functions.
53 ga_get_struct_whatever() should be renamed to ga_struct_get_whatever().
54
55 **********************************************************************/
56
57 #include "gaul/ga_core.h"
58
59 /*
60 * Global variables.
61 */
62 static TableStruct *pop_table=NULL; /* The population table. */
63
64 THREAD_LOCK_DEFINE_STATIC(pop_table_lock);
65 #ifdef USE_OPENMP
66 static boolean gaul_openmp_initialised = FALSE;
67 #endif
68
69 /*
70 * Lookup table for functions.
71 *
72 * This is required for saving defined code hooks in files and for
73 * some script interfaces.
74 */
75 struct func_lookup {char *funcname; void *func_ptr;};
76
77 static struct func_lookup lookup[]={
78 { NULL, NULL },
79 { "ga_select_one_random", (void *) ga_select_one_random },
80 { "ga_select_two_random", (void *) ga_select_two_random },
81 { "ga_select_one_every", (void *) ga_select_one_every },
82 { "ga_select_two_every", (void *) ga_select_two_every },
83 { "ga_select_one_randomrank", (void *) ga_select_one_randomrank },
84 { "ga_select_two_randomrank", (void *) ga_select_two_randomrank },
85 { "ga_select_one_bestof2", (void *) ga_select_one_bestof2 },
86 { "ga_select_two_bestof2", (void *) ga_select_two_bestof2 },
87 { "ga_select_one_bestof3", (void *) ga_select_one_bestof3 },
88 { "ga_select_two_bestof3", (void *) ga_select_two_bestof3 },
89 { "ga_select_one_roulette", (void *) ga_select_one_roulette },
90 { "ga_select_two_roulette", (void *) ga_select_two_roulette },
91 { "ga_select_one_roulette_rebased", (void *) ga_select_one_roulette_rebased },
92 { "ga_select_two_roulette_rebased", (void *) ga_select_two_roulette_rebased },
93 { "ga_select_one_sus", (void *) ga_select_one_sus },
94 { "ga_select_two_sus", (void *) ga_select_two_sus },
95 { "ga_select_one_sussq", (void *) ga_select_one_sussq },
96 { "ga_select_two_sussq", (void *) ga_select_two_sussq },
97 { "ga_select_one_best", (void *) ga_select_one_best },
98 { "ga_select_two_best", (void *) ga_select_two_best },
99 { "ga_select_one_aggressive", (void *) ga_select_one_aggressive },
100 { "ga_select_two_aggressive", (void *) ga_select_two_aggressive },
101 { "ga_select_one_linearrank", (void *) ga_select_one_linearrank },
102 { "ga_select_two_linearrank", (void *) ga_select_two_linearrank },
103 { "ga_select_one_roundrobin", (void *) ga_select_one_roundrobin },
104 { "ga_crossover_integer_singlepoints", (void *) ga_crossover_integer_singlepoints },
105 { "ga_crossover_integer_doublepoints", (void *) ga_crossover_integer_doublepoints },
106 { "ga_crossover_integer_mean", (void *) ga_crossover_integer_mean },
107 { "ga_crossover_integer_mixing", (void *) ga_crossover_integer_mixing },
108 { "ga_crossover_integer_allele_mixing", (void *) ga_crossover_integer_allele_mixing },
109 { "ga_crossover_boolean_singlepoints", (void *) ga_crossover_boolean_singlepoints },
110 { "ga_crossover_boolean_doublepoints", (void *) ga_crossover_boolean_doublepoints },
111 { "ga_crossover_boolean_mixing", (void *) ga_crossover_boolean_mixing },
112 { "ga_crossover_boolean_allele_mixing", (void *) ga_crossover_boolean_allele_mixing },
113 { "ga_crossover_char_singlepoints", (void *) ga_crossover_char_singlepoints },
114 { "ga_crossover_char_doublepoints", (void *) ga_crossover_char_doublepoints },
115 { "ga_crossover_char_mixing", (void *) ga_crossover_char_mixing },
116 { "ga_crossover_char_allele_mixing", (void *) ga_crossover_char_allele_mixing },
117 { "ga_crossover_double_mean", (void *) ga_crossover_double_mean },
118 { "ga_crossover_double_mixing", (void *) ga_crossover_double_mixing },
119 { "ga_crossover_double_allele_mixing", (void *) ga_crossover_double_allele_mixing },
120 { "ga_crossover_double_singlepoints", (void *) ga_crossover_double_singlepoints },
121 { "ga_crossover_double_doublepoints", (void *) ga_crossover_double_doublepoints },
122 { "ga_crossover_bitstring_singlepoints", (void *) ga_crossover_bitstring_singlepoints },
123 { "ga_crossover_bitstring_doublepoints", (void *) ga_crossover_bitstring_doublepoints },
124 { "ga_crossover_bitstring_mixing", (void *) ga_crossover_bitstring_mixing },
125 { "ga_crossover_bitstring_allele_mixing", (void *) ga_crossover_bitstring_allele_mixing },
126 { "ga_mutate_integer_singlepoint_drift", (void *) ga_mutate_integer_singlepoint_drift },
127 { "ga_mutate_integer_singlepoint_randomize", (void *) ga_mutate_integer_singlepoint_randomize },
128 { "ga_mutate_integer_multipoint", (void *) ga_mutate_integer_multipoint },
129 { "ga_mutate_integer_allpoint", (void *) ga_mutate_integer_allpoint },
130 { "ga_mutate_boolean_singlepoint", (void *) ga_mutate_boolean_singlepoint },
131 { "ga_mutate_boolean_multipoint", (void *) ga_mutate_boolean_multipoint },
132 { "ga_mutate_char_singlepoint_drift", (void *) ga_mutate_char_singlepoint_drift },
133 { "ga_mutate_char_singlepoint_randomize", (void *) ga_mutate_char_singlepoint_randomize },
134 { "ga_mutate_char_allpoint", (void *) ga_mutate_char_allpoint },
135 { "ga_mutate_char_multipoint", (void *) ga_mutate_char_multipoint },
136 { "ga_mutate_printable_singlepoint_drift", (void *) ga_mutate_printable_singlepoint_drift },
137 { "ga_mutate_printable_singlepoint_randomize", (void *) ga_mutate_printable_singlepoint_randomize },
138 { "ga_mutate_printable_multipoint", (void *) ga_mutate_printable_multipoint },
139 { "ga_mutate_printable_allpoint", (void *) ga_mutate_printable_allpoint },
140 { "ga_mutate_bitstring_singlepoint", (void *) ga_mutate_bitstring_singlepoint },
141 { "ga_mutate_bitstring_multipoint", (void *) ga_mutate_bitstring_multipoint },
142 { "ga_mutate_double_singlepoint_randomize", (void *) ga_mutate_double_singlepoint_randomize },
143 { "ga_mutate_double_singlepoint_drift", (void *) ga_mutate_double_singlepoint_drift },
144 { "ga_mutate_double_allpoint", (void *) ga_mutate_double_allpoint },
145 { "ga_mutate_double_multipoint", (void *) ga_mutate_double_multipoint },
146 { "ga_seed_boolean_random", (void *) ga_seed_boolean_random },
147 { "ga_seed_boolean_zero", (void *) ga_seed_boolean_zero },
148 { "ga_seed_integer_random", (void *) ga_seed_integer_random },
149 { "ga_seed_integer_zero", (void *) ga_seed_integer_zero },
150 { "ga_seed_double_random", (void *) ga_seed_double_random },
151 { "ga_seed_double_zero", (void *) ga_seed_double_zero },
152 { "ga_seed_double_random_unit_gaussian", (void *) ga_seed_double_random_unit_gaussian },
153 { "ga_seed_char_random", (void *) ga_seed_char_random },
154 { "ga_seed_printable_random", (void *) ga_seed_printable_random },
155 { "ga_seed_bitstring_random", (void *) ga_seed_bitstring_random },
156 { "ga_seed_bitstring_zero", (void *) ga_seed_bitstring_zero },
157 { "ga_replace_by_fitness", (void *) ga_replace_by_fitness },
158 { "ga_rank_fitness", (void *) ga_rank_fitness },
159 { "ga_chromosome_integer_allocate", (void *) ga_chromosome_integer_allocate },
160 { "ga_chromosome_integer_deallocate", (void *) ga_chromosome_integer_deallocate },
161 { "ga_chromosome_integer_replicate", (void *) ga_chromosome_integer_replicate },
162 { "ga_chromosome_integer_to_bytes", (void *) ga_chromosome_integer_to_bytes },
163 { "ga_chromosome_integer_from_bytes", (void *) ga_chromosome_integer_from_bytes },
164 { "ga_chromosome_integer_to_string", (void *) ga_chromosome_integer_to_string },
165 { "ga_chromosome_boolean_allocate", (void *) ga_chromosome_boolean_allocate },
166 { "ga_chromosome_boolean_deallocate", (void *) ga_chromosome_boolean_deallocate },
167 { "ga_chromosome_boolean_replicate", (void *) ga_chromosome_boolean_replicate },
168 { "ga_chromosome_boolean_to_bytes", (void *) ga_chromosome_boolean_to_bytes },
169 { "ga_chromosome_boolean_from_bytes", (void *) ga_chromosome_boolean_from_bytes },
170 { "ga_chromosome_boolean_to_string", (void *) ga_chromosome_boolean_to_string },
171 { "ga_chromosome_double_allocate", (void *) ga_chromosome_double_allocate },
172 { "ga_chromosome_double_deallocate", (void *) ga_chromosome_double_deallocate },
173 { "ga_chromosome_double_replicate", (void *) ga_chromosome_double_replicate },
174 { "ga_chromosome_double_to_bytes", (void *) ga_chromosome_double_to_bytes },
175 { "ga_chromosome_double_from_bytes", (void *) ga_chromosome_double_from_bytes },
176 { "ga_chromosome_double_to_string", (void *) ga_chromosome_double_to_string },
177 { "ga_chromosome_char_allocate", (void *) ga_chromosome_char_allocate },
178 { "ga_chromosome_char_deallocate", (void *) ga_chromosome_char_deallocate },
179 { "ga_chromosome_char_replicate", (void *) ga_chromosome_char_replicate },
180 { "ga_chromosome_char_to_bytes", (void *) ga_chromosome_char_to_bytes },
181 { "ga_chromosome_char_from_bytes", (void *) ga_chromosome_char_from_bytes },
182 { "ga_chromosome_char_to_string", (void *) ga_chromosome_char_to_string },
183 { "ga_chromosome_bitstring_allocate", (void *) ga_chromosome_bitstring_allocate },
184 { "ga_chromosome_bitstring_deallocate", (void *) ga_chromosome_bitstring_deallocate },
185 { "ga_chromosome_bitstring_replicate", (void *) ga_chromosome_bitstring_replicate },
186 { "ga_chromosome_bitstring_to_bytes", (void *) ga_chromosome_bitstring_to_bytes },
187 { "ga_chromosome_bitstring_from_bytes", (void *) ga_chromosome_bitstring_from_bytes },
188 { "ga_chromosome_bitstring_to_string", (void *) ga_chromosome_bitstring_to_string },
189 { "ga_chromosome_list_allocate", (void *) ga_chromosome_list_allocate },
190 { "ga_chromosome_list_deallocate", (void *) ga_chromosome_list_deallocate },
191 { "ga_chromosome_list_replicate", (void *) ga_chromosome_list_replicate },
192 { "ga_chromosome_list_to_bytes", (void *) ga_chromosome_list_to_bytes },
193 { "ga_chromosome_list_from_bytes", (void *) ga_chromosome_list_from_bytes },
194 { "ga_chromosome_list_to_string", (void *) ga_chromosome_list_to_string },
195 { NULL, NULL } };
196
197
198 /**********************************************************************
199 Private utility functions.
200 **********************************************************************/
201
202 /**********************************************************************
203 destruct_list()
204 synopsis: Destroys an userdata list and it's contents. For
205 many applications, the destructor callback will just
206 be free() or similar. This callback may safely be
207 NULL.
208 parameters: population *pop Population.
209 SLList *list Phenomic data.
210 return: none
211 last updated: 24 Aug 2002
212 **********************************************************************/
213
destruct_list(population * pop,SLList * list)214 static void destruct_list(population *pop, SLList *list)
215 {
216 SLList *present; /* Current list element */
217 int num_destroyed; /* Count number of things destroyed. */
218 vpointer data; /* Data in item. */
219
220 /* A bit of validation. */
221 if ( !pop ) die("Null pointer to population structure passed.");
222 if ( !list ) die("Null pointer to list passed.");
223
224 /*
225 * Deallocate data stored in the list, if required.
226 */
227 if ( pop->data_destructor )
228 {
229 num_destroyed = 0;
230 present=list;
231
232 while(present!=NULL)
233 {
234 if ((data = slink_data(present)))
235 {
236 pop->data_destructor(data);
237 num_destroyed++;
238 }
239 present=slink_next(present);
240 }
241
242 #if GA_DEBUG>2
243 /*
244 * Not typically needed now, because num_destrtoyed may
245 * (correctly) differ from the actual number of chromosomes.
246 */
247 if (num_destroyed != pop->num_chromosomes)
248 printf("Uh oh! Dodgy user data here? %d %d\n",
249 num_destroyed, pop->num_chromosomes);
250 #endif
251
252 }
253
254 /* Deallocate the list sructure. */
255 slink_free_all(list);
256
257 return;
258 }
259
260
261 /**********************************************************************
262 Population handling functions.
263 **********************************************************************/
264
265 /**********************************************************************
266 ga_population_new()
267 synopsis: Allocates and initialises a new population structure,
268 and assigns a new population id to it.
269 parameters: const int stable_size Num. individuals carried into next generation.
270 const int num_chromosome Num. of chromosomes.
271 const int len_chromosome Size of chromosomes (may be ignored).
272 return: population * new population structure.
273 last updated: 16 Feb 2005
274 **********************************************************************/
275
ga_population_new(const int stable_size,const int num_chromosome,const int len_chromosome)276 population *ga_population_new( const int stable_size,
277 const int num_chromosome,
278 const int len_chromosome)
279 {
280 population *newpop=NULL; /* New population structure. */
281 unsigned int pop_id; /* Handle for new population structure. */
282 int i; /* Loop over (unassigned) entities. */
283
284 if ( !(newpop = s_malloc(sizeof(population))) )
285 die("Unable to allocate memory");
286
287 newpop->size = 0;
288 newpop->stable_size = stable_size;
289 newpop->max_size = (1+stable_size)*4; /* +1 prevents problems if stable_size is 0. */
290 newpop->orig_size = 0;
291 newpop->num_chromosomes = num_chromosome;
292 newpop->len_chromosomes = len_chromosome;
293 newpop->data = NULL;
294 newpop->free_index = newpop->max_size-1;
295 newpop->island = -1;
296 newpop->generation = 0;
297
298 newpop->crossover_ratio = GA_DEFAULT_CROSSOVER_RATIO;
299 newpop->mutation_ratio = GA_DEFAULT_MUTATION_RATIO;
300 newpop->migration_ratio = GA_DEFAULT_MIGRATION_RATIO;
301 newpop->scheme = GA_SCHEME_DARWIN;
302 newpop->elitism = GA_ELITISM_PARENTS_SURVIVE;
303
304 newpop->allele_mutation_prob = GA_DEFAULT_ALLELE_MUTATION_PROB;
305 newpop->allele_min_integer = 0;
306 newpop->allele_max_integer = RAND_MAX-1; /* this may seem like an odd choice, but it is to maintain compatiability with older versions. */
307 newpop->allele_min_double = DBL_MIN;
308 newpop->allele_max_double = DBL_MAX;
309
310 THREAD_LOCK_NEW(newpop->lock);
311 #if USE_CHROMO_CHUNKS == 1
312 THREAD_LOCK_NEW(newpop->chromo_chunk_lock);
313 #endif
314
315 if ( !(newpop->entity_array = s_malloc(newpop->max_size*sizeof(entity*))) )
316 die("Unable to allocate memory");
317
318 if ( !(newpop->entity_iarray = s_malloc(newpop->max_size*sizeof(entity*))) )
319 die("Unable to allocate memory");
320
321 newpop->entity_chunk = mem_chunk_new(sizeof(entity), 512);
322
323 /*
324 * Wipe the entity arrays.
325 */
326 for (i=0; i<newpop->max_size; i++)
327 {
328 newpop->entity_array[i] = NULL;
329 newpop->entity_iarray[i] = NULL;
330 }
331
332 /*
333 * Wipe optional parameter data.
334 */
335 newpop->tabu_params = NULL;
336 newpop->sa_params = NULL;
337 newpop->climbing_params = NULL;
338 newpop->simplex_params = NULL;
339 newpop->dc_params = NULL;
340 newpop->gradient_params = NULL;
341 newpop->search_params = NULL;
342 newpop->sampling_params = NULL;
343
344 /*
345 * Clean the callback functions.
346 * Prevents erronerous callbacks - helpful when debugging!
347 */
348 newpop->generation_hook = NULL;
349 newpop->iteration_hook = NULL;
350
351 newpop->data_destructor = NULL;
352 newpop->data_ref_incrementor = NULL;
353
354 newpop->chromosome_constructor = NULL;
355 newpop->chromosome_destructor = NULL;
356 newpop->chromosome_replicate = NULL;
357 newpop->chromosome_to_bytes = NULL;
358 newpop->chromosome_from_bytes = NULL;
359 newpop->chromosome_to_string = NULL;
360
361 newpop->evaluate = NULL;
362 newpop->seed = NULL;
363 newpop->adapt = NULL;
364 newpop->select_one = NULL;
365 newpop->select_two = NULL;
366 newpop->mutate = NULL;
367 newpop->crossover = NULL;
368 newpop->replace = NULL;
369 newpop->rank = ga_rank_fitness;
370
371 /*
372 * Efficient memory chunks for chromosome handling.
373 */
374 #if USE_CHROMO_CHUNKS == 1
375 newpop->chromoarray_chunk = NULL;
376 newpop->chromo_chunk = NULL;
377 #endif
378
379 /*
380 * Add this new population into the population table.
381 */
382 THREAD_LOCK(pop_table_lock);
383 if ( !pop_table ) pop_table=table_new();
384
385 pop_id = table_add(pop_table, (vpointer) newpop);
386 THREAD_UNLOCK(pop_table_lock);
387
388 plog( LOG_DEBUG, "New pop = %p id = %d", newpop, pop_id);
389
390 return newpop;
391 }
392
393
394 /**********************************************************************
395 ga_population_clone_empty()
396 synopsis: Allocates and initialises a new population structure,
397 and fills it with an exact copy of the data from an
398 existing population, with the exception that entity
399 data is not copied. The population's user data
400 field is referenced.
401 parameters: population * original population structure.
402 return: population * new population structure.
403 last updated: 16 Feb 2005
404 **********************************************************************/
405
ga_population_clone_empty(population * pop)406 population *ga_population_clone_empty(population *pop)
407 {
408 int i; /* Loop variable. */
409 population *newpop=NULL; /* New population structure. */
410 unsigned int pop_id; /* Handle for new population structure. */
411
412 /* Checks */
413 if ( !pop ) die("Null pointer to population structure passed.");
414
415 /*
416 * Allocate new structure.
417 */
418 newpop = s_malloc(sizeof(population));
419
420 /*
421 * Clone parameters.
422 */
423 newpop->size = 0;
424 newpop->stable_size = pop->stable_size;
425 newpop->max_size = pop->max_size;
426 newpop->orig_size = 0;
427 newpop->num_chromosomes = pop->num_chromosomes;
428 newpop->len_chromosomes = pop->len_chromosomes;
429 newpop->data = pop->data;
430 newpop->free_index = pop->max_size-1;
431
432 newpop->crossover_ratio = pop->crossover_ratio;
433 newpop->mutation_ratio = pop->mutation_ratio;
434 newpop->migration_ratio = pop->migration_ratio;
435 newpop->scheme = pop->scheme;
436 newpop->elitism = pop->elitism;
437
438 newpop->allele_mutation_prob = pop->allele_mutation_prob;
439 newpop->allele_min_integer = newpop->allele_min_integer;
440 newpop->allele_max_integer = newpop->allele_max_integer;
441 newpop->allele_min_double = newpop->allele_min_double;
442 newpop->allele_max_double = newpop->allele_max_double;
443
444 THREAD_LOCK_NEW(newpop->lock);
445 #if USE_CHROMO_CHUNKS == 1
446 THREAD_LOCK_NEW(newpop->chromo_chunk_lock);
447 #endif
448
449 /*
450 * Clone the callback functions.
451 */
452 newpop->generation_hook = pop->generation_hook;
453 newpop->iteration_hook = pop->iteration_hook;
454
455 newpop->data_destructor = pop->data_destructor;
456 newpop->data_ref_incrementor = pop->data_ref_incrementor;
457
458 newpop->chromosome_constructor = pop->chromosome_constructor;
459 newpop->chromosome_destructor = pop->chromosome_destructor;
460 newpop->chromosome_replicate = pop->chromosome_replicate;
461 newpop->chromosome_to_bytes = pop->chromosome_to_bytes;
462 newpop->chromosome_from_bytes = pop->chromosome_from_bytes;
463 newpop->chromosome_to_string = pop->chromosome_to_string;
464
465 newpop->evaluate = pop->evaluate;
466 newpop->seed = pop->seed;
467 newpop->adapt = pop->adapt;
468 newpop->select_one = pop->select_one;
469 newpop->select_two = pop->select_two;
470 newpop->mutate = pop->mutate;
471 newpop->crossover = pop->crossover;
472 newpop->replace = pop->replace;
473 newpop->rank = pop->rank;
474
475 /*
476 * Copy optional parameter data.
477 */
478 if (pop->tabu_params == NULL)
479 {
480 newpop->tabu_params = NULL;
481 }
482 else
483 {
484 newpop->tabu_params = s_malloc(sizeof(ga_tabu_t));
485
486 newpop->tabu_params->tabu_accept = pop->tabu_params->tabu_accept;
487 newpop->tabu_params->list_length = pop->tabu_params->list_length;
488 newpop->tabu_params->search_count = pop->tabu_params->search_count;
489 }
490
491 if (pop->sa_params == NULL)
492 {
493 newpop->sa_params = NULL;
494 }
495 else
496 {
497 newpop->sa_params = s_malloc(sizeof(ga_sa_t));
498 newpop->sa_params->sa_accept = pop->sa_params->sa_accept;
499 newpop->sa_params->initial_temp = pop->sa_params->initial_temp;
500 newpop->sa_params->final_temp = pop->sa_params->final_temp;
501 newpop->sa_params->temp_step = pop->sa_params->temp_step;
502 newpop->sa_params->temp_freq = pop->sa_params->temp_freq;
503 newpop->sa_params->temperature = pop->sa_params->temperature;
504 }
505
506 if (pop->climbing_params == NULL)
507 {
508 newpop->climbing_params = NULL;
509 }
510 else
511 {
512 newpop->climbing_params = s_malloc(sizeof(ga_climbing_t));
513
514 newpop->climbing_params->mutate_allele = pop->climbing_params->mutate_allele;
515 }
516
517 if (pop->simplex_params == NULL)
518 {
519 newpop->simplex_params = NULL;
520 }
521 else
522 {
523 newpop->simplex_params = s_malloc(sizeof(ga_simplex_t));
524
525 newpop->climbing_params->mutate_allele = pop->climbing_params->mutate_allele;
526 newpop->simplex_params->to_double = pop->simplex_params->to_double;
527 newpop->simplex_params->from_double = pop->simplex_params->from_double;
528 newpop->simplex_params->dimensions = pop->simplex_params->dimensions;
529 }
530
531 if (pop->dc_params == NULL)
532 {
533 newpop->dc_params = NULL;
534 }
535 else
536 {
537 newpop->dc_params = s_malloc(sizeof(ga_dc_t));
538
539 newpop->dc_params->compare = pop->dc_params->compare;
540 }
541
542 if (pop->gradient_params == NULL)
543 {
544 newpop->gradient_params = NULL;
545 }
546 else
547 {
548 newpop->gradient_params = s_malloc(sizeof(ga_gradient_t));
549
550 newpop->gradient_params->to_double = newpop->gradient_params->to_double;
551 newpop->gradient_params->from_double = newpop->gradient_params->from_double;
552 newpop->gradient_params->gradient = newpop->gradient_params->gradient;
553 newpop->gradient_params->step_size = newpop->gradient_params->step_size;
554 newpop->gradient_params->dimensions = newpop->gradient_params->dimensions;
555 }
556
557 if (pop->search_params == NULL)
558 {
559 newpop->search_params = NULL;
560 }
561 else
562 {
563 newpop->search_params = s_malloc(sizeof(ga_search_t));
564
565 newpop->search_params->scan_chromosome = pop->search_params->scan_chromosome;
566 newpop->search_params->chromosome_state = 0;
567 newpop->search_params->allele_state = 0;
568 }
569
570 if (newpop->sampling_params == NULL)
571 {
572 newpop->sampling_params = NULL;
573 }
574 else
575 {
576 newpop->sampling_params = NULL;
577
578 plog(LOG_FIXME, "Probabilistic sampling parameters not copied.");
579 }
580
581 /*
582 * Allocate arrays etc.
583 */
584 newpop->entity_array = s_malloc(newpop->max_size*sizeof(entity*));
585 newpop->entity_iarray = s_malloc(newpop->max_size*sizeof(entity*));
586 newpop->entity_chunk = mem_chunk_new(sizeof(entity), 512);
587
588 /*
589 * Wipe the the entity arrays.
590 */
591 for (i=0; i<newpop->max_size; i++)
592 {
593 newpop->entity_array[i] = NULL;
594 newpop->entity_iarray[i] = NULL;
595 }
596
597 /*
598 * Add this new population into the population table.
599 */
600 THREAD_LOCK(pop_table_lock);
601 if ( !pop_table ) pop_table=table_new();
602
603 pop_id = table_add(pop_table, (vpointer) newpop);
604 THREAD_UNLOCK(pop_table_lock);
605
606 plog( LOG_DEBUG, "New pop = %p id = %d (cloned from %p)",
607 newpop, pop_id, pop );
608
609 return newpop;
610 }
611
612
613 /**********************************************************************
614 ga_population_clone()
615 synopsis: Allocates and initialises a new population structure,
616 and fills it with an exact copy of the data from an
617 existing population, including the individual
618 entity data. The population's user data
619 field is referenced.
620 Entity id's between the populations will _NOT_
621 correspond.
622 parameters: population * original population structure.
623 return: population * new population structure.
624 last updated: 24 May 2002
625 **********************************************************************/
626
ga_population_clone(population * pop)627 population *ga_population_clone(population *pop)
628 {
629 int i; /* Loop variable. */
630 population *newpop=NULL; /* New population structure. */
631 entity *newentity; /* Used for cloning entities. */
632
633 /* Note that checks are performed in the ga_population_clone_empty() function. */
634
635 /*
636 * Clone the population data.
637 */
638 newpop = ga_population_clone_empty(pop);
639
640 /*
641 * Clone each of the constituent entities.
642 */
643 #pragma omp parallel for \
644 shared(pop,newpop) private(i,newentity) \
645 schedule(static)
646 for (i=0; i<pop->size; i++)
647 {
648 newentity = ga_get_free_entity(newpop);
649 ga_entity_copy(newpop, newentity, pop->entity_iarray[i]);
650 }
651
652 return newpop;
653 }
654
655
656 /**********************************************************************
657 ga_get_num_populations()
658 synopsis: Gets the number of populations.
659 parameters: none
660 return: int number of populations, -1 for undefined table.
661 last updated: 15 Aug 2002
662 **********************************************************************/
663
ga_get_num_populations(void)664 int ga_get_num_populations(void)
665 {
666 int num=-1;
667
668 THREAD_LOCK(pop_table_lock);
669 if (pop_table)
670 {
671 num = table_count_items(pop_table);
672 }
673 THREAD_UNLOCK(pop_table_lock);
674
675 return num;
676 }
677
678
679 /**********************************************************************
680 ga_get_population_from_id()
681 synopsis: Get population pointer from its internal id.
682 parameters: unsigned int id for population.
683 return: int
684 last updated: 15 Aug 2002
685 **********************************************************************/
686
ga_get_population_from_id(unsigned int id)687 population *ga_get_population_from_id(unsigned int id)
688 {
689 population *pop=NULL; /* The population pointer to return. */
690
691 THREAD_LOCK(pop_table_lock);
692 if (pop_table)
693 {
694 pop = (population *) table_get_data(pop_table, id);
695 }
696 THREAD_UNLOCK(pop_table_lock);
697
698 return pop;
699 }
700
701
702 /**********************************************************************
703 ga_get_population_id()
704 synopsis: Get population's internal id from its pointer.
705 parameters: population population pointer to lookup.
706 return: unsigned int internal id for population (or -1 for no match).
707 last updated: 15 Aug 2002
708 **********************************************************************/
709
ga_get_population_id(population * pop)710 unsigned int ga_get_population_id(population *pop)
711 {
712 unsigned int id=TABLE_ERROR_INDEX; /* Internal population id. */
713
714 THREAD_LOCK(pop_table_lock);
715 if (pop_table && pop)
716 {
717 id = table_lookup_index(pop_table, (vpointer) pop);
718 }
719 THREAD_UNLOCK(pop_table_lock);
720
721 return id;
722 }
723
724
725 /**********************************************************************
726 ga_get_all_population_ids()
727 synopsis: Get array of internal ids for all currently
728 allocated populations. The returned array needs to
729 be deallocated by the caller.
730 parameters: none
731 return: unsigned int* array of population ids (or NULL)
732 last updated: 15 Aug 2002
733 **********************************************************************/
734
ga_get_all_population_ids(void)735 unsigned int *ga_get_all_population_ids(void)
736 {
737 unsigned int *ids=NULL; /* Array of ids. */
738
739 THREAD_LOCK(pop_table_lock);
740 if (pop_table)
741 {
742 ids = table_get_index_all(pop_table);
743 }
744 THREAD_UNLOCK(pop_table_lock);
745
746 return ids;
747 }
748
749
750 /**********************************************************************
751 ga_get_all_populations()
752 synopsis: Get array of all currently allocated populations. The
753 returned array needs to be deallocated by the caller.
754 parameters: none
755 return: population** array of population pointers
756 last updated: 15 Aug 2002
757 **********************************************************************/
758
ga_get_all_populations(void)759 population **ga_get_all_populations(void)
760 {
761 population **pops=NULL; /* Array of all population pointers. */
762
763 THREAD_LOCK(pop_table_lock);
764 if (pop_table)
765 {
766 pops = (population **) table_get_data_all(pop_table);
767 }
768 THREAD_UNLOCK(pop_table_lock);
769
770 return pops;
771 }
772
773
774 /**********************************************************************
775 ga_entity_seed()
776 synopsis: Fills a population structure with genes. Defined in
777 a user-specified function.
778 parameters: population * The entity's population.
779 entity * The entity.
780 return: boolean success.
781 last updated: 28/02/01
782 **********************************************************************/
783
ga_entity_seed(population * pop,entity * adam)784 boolean ga_entity_seed(population *pop, entity *adam)
785 {
786
787 if ( !pop ) die("Null pointer to population structure passed.");
788 if ( !pop->seed ) die("Population seeding function is not defined.");
789
790 return pop->seed(pop, adam);
791 }
792
793
794 /**********************************************************************
795 gaul_population_fill()
796 synopsis: Fills all entities in a population structure with
797 genes from a user-specified function.
798 parameters: population *pop
799 int num Number of entities to seed.
800 return: boolean success.
801 last updated: 17 Feb 2005
802 **********************************************************************/
803
gaul_population_fill(population * pop,int num)804 boolean gaul_population_fill(population *pop, int num)
805 {
806 int i; /* Loop variables. */
807 entity *adam; /* New population member. */
808
809 plog(LOG_DEBUG, "Population seeding by user-defined genesis.");
810
811 if ( !pop ) die("Null pointer to population structure passed.");
812 if ( !pop->seed ) die("Population seeding function is not defined.");
813
814 /* NOTE: OpenMP adjusts order of seeding operations here, and therefore alters results. */
815 #pragma omp parallel for \
816 if (GAUL_DETERMINISTIC_OPENMP==0) \
817 shared(pop, num) private(i,adam) \
818 schedule(static)
819 for (i=0; i<num; i++)
820 {
821 /*printf("DEBUG: ga_population_seed() parallel for %d on %d/%d.\n", i, omp_get_thread_num(), omp_get_num_threads());*/
822 adam = ga_get_free_entity(pop);
823 pop->seed(pop, adam);
824 }
825
826 return TRUE;
827 }
828
829
830 /**********************************************************************
831 ga_population_seed()
832 synopsis: Fills all entities in a population structure with
833 genes from a user-specified function.
834 parameters: population
835 return: boolean success.
836 last updated: 24 Feb 2005
837 **********************************************************************/
838
ga_population_seed(population * pop)839 boolean ga_population_seed(population *pop)
840 {
841
842 plog(LOG_DEBUG, "Population seeding by user-defined genesis.");
843
844 return gaul_population_fill(pop, pop->stable_size);
845 }
846
847
848 /**********************************************************************
849 ga_funclookup_ptr_to_id()
850 synopsis: Assign a unique id to a callback function for
851 population disk format from its pointer.
852 parameters:
853 return:
854 last updated: 10 Apr 2003
855 **********************************************************************/
856
ga_funclookup_ptr_to_id(void * func)857 int ga_funclookup_ptr_to_id(void *func)
858 {
859 int id=1; /* Index into lookup table. */
860
861 if ( !func ) return 0;
862
863 while (lookup[id].func_ptr != NULL &&
864 func != lookup[id].func_ptr)
865 id++;
866
867 #if GA_DEBUG>2
868 printf("Function id is %d\n", id);
869 #endif
870
871 return lookup[id].func_ptr!=NULL?id:-1;
872 }
873
874
875 /**********************************************************************
876 ga_funclookup_label_to_id()
877 synopsis: Assign a unique id to a callback function for
878 population disk format from its label.
879 parameters:
880 return:
881 last updated: 10 Apr 2003
882 **********************************************************************/
883
ga_funclookup_label_to_id(char * funcname)884 int ga_funclookup_label_to_id(char *funcname)
885 {
886 int id=1; /* Index into lookup table. */
887
888 if ( !funcname ) return 0;
889
890 while (lookup[id].funcname != NULL &&
891 strcmp(funcname, lookup[id].funcname) != 0)
892 id++;
893
894 #if GA_DEBUG>2
895 printf("Function id is %d\n", id);
896 #endif
897
898 return lookup[id].func_ptr!=NULL?id:-1;
899 }
900
901
902 /**********************************************************************
903 ga_funclookup_label_to_ptr()
904 synopsis: Return the pointer to a callback function
905 from its label.
906 parameters:
907 return:
908 last updated: 10 Apr 2003
909 **********************************************************************/
910
ga_funclookup_label_to_ptr(char * funcname)911 void *ga_funclookup_label_to_ptr(char *funcname)
912 {
913 int id=1; /* Index into lookup table. */
914
915 if ( !funcname ) return 0;
916
917 while (lookup[id].funcname != NULL &&
918 strcmp(funcname, lookup[id].funcname) != 0)
919 id++;
920
921 #if GA_DEBUG>2
922 printf("Function id is %d\n", id);
923 #endif
924
925 return lookup[id].func_ptr;
926 }
927
928
929 /**********************************************************************
930 ga_funclookup_id_to_ptr()
931 synopsis: Returns the pointer to a function from its unique id.
932 parameters:
933 return:
934 last updated: 10 Apr 2003
935 **********************************************************************/
936
ga_funclookup_id_to_ptr(int id)937 void *ga_funclookup_id_to_ptr(int id)
938 {
939
940 #if GA_DEBUG>2
941 printf("Looking for function with id %d\n", id);
942 #endif
943
944 return (id<0)?NULL:lookup[id].func_ptr;
945 }
946
947
948 /**********************************************************************
949 ga_funclookup_id_to_label()
950 synopsis: Returns the label for a function from its unique id.
951 parameters:
952 return:
953 last updated: 10 Apr 2003
954 **********************************************************************/
955
ga_funclookup_id_to_label(int id)956 char *ga_funclookup_id_to_label(int id)
957 {
958
959 #if GA_DEBUG>2
960 printf("Looking for function with id %d\n", id);
961 #endif
962
963 return (id<0)?NULL:lookup[id].funcname;
964 }
965
966
967 /**********************************************************************
968 ga_entity_evaluate()
969 synopsis: Score a single entity.
970 parameters: population *pop
971 entity *entity
972 return: double the fitness
973 last updated: 01 Jul 2004
974 **********************************************************************/
975
ga_entity_evaluate(population * pop,entity * entity)976 double ga_entity_evaluate(population *pop, entity *entity)
977 {
978
979 if ( !pop ) die("Null pointer to population structure passed.");
980 if ( !entity ) die("Null pointer to entity structure passed.");
981 if ( !pop->evaluate ) die("Evaluation callback not defined.");
982
983 if (pop->evaluate(pop, entity) == FALSE)
984 entity->fitness = GA_MIN_FITNESS;
985
986 return entity->fitness;
987 }
988
989
990 /**********************************************************************
991 ga_population_score_and_sort()
992 synopsis: Score and sort entire population. This is probably
993 a good idea after changing the fitness function!
994 Note: remember to define the callback functions first.
995 parameters:
996 return:
997 last updated: 28/02/01
998 **********************************************************************/
999
ga_population_score_and_sort(population * pop)1000 boolean ga_population_score_and_sort(population *pop)
1001 {
1002 int i; /* Loop variable over all entities. */
1003 #if GA_DEBUG>2
1004 double origfitness; /* Stored fitness value. */
1005 #endif
1006
1007 /* Checks. */
1008 if ( !pop ) die("Null pointer to population structure passed.");
1009 if ( !pop->evaluate ) die("Evaluation callback not defined.");
1010
1011 /*
1012 * Score and sort all of the population members.
1013 *
1014 * Note that this will (potentially) use a huge amount of memory more
1015 * than the original population data if the userdata hasn't been maintained.
1016 * Each chromosome is decoded separately, whereas originally many
1017 * degenerate chromosomes would share their userdata elements.
1018 */
1019 #pragma omp parallel for \
1020 shared(pop) private(i) \
1021 schedule(static)
1022 for (i=0; i<pop->size; i++)
1023 {
1024 #if GA_DEBUG>2
1025 origfitness = pop->entity_iarray[i]->fitness;
1026 #endif
1027 pop->evaluate(pop, pop->entity_iarray[i]);
1028
1029 #if GA_DEBUG>2
1030 if (origfitness != pop->entity_iarray[i]->fitness)
1031 plog(LOG_NORMAL,
1032 "Recalculated fitness %f doesn't match stored fitness %f for entity %d.",
1033 pop->entity_iarray[i]->fitness, origfitness, i);
1034 #endif
1035 }
1036
1037 sort_population(pop);
1038
1039 return TRUE;
1040 }
1041
1042
1043 /**********************************************************************
1044 ga_population_sort()
1045 synopsis: Sort entire population (i.e. ensure that the entities
1046 are correctly ordered in ranking array -- currently
1047 rank is defined only by fitness).
1048 Note: remember to define the callback functions first.
1049 parameters:
1050 return:
1051 last updated: 30 May 2002
1052 **********************************************************************/
1053
ga_population_sort(population * pop)1054 boolean ga_population_sort(population *pop)
1055 {
1056
1057 /* Checks. */
1058 if ( !pop ) die("Null pointer to population structure passed.");
1059
1060 sort_population(pop);
1061
1062 return TRUE;
1063 }
1064
1065
1066 #if 0
1067 FIXME: The following 3 functions need to be fixed for the new absracted chromosome types.
1068 /**********************************************************************
1069 ga_population_convergence_genotypes()
1070 synopsis: Determine ratio of converged genotypes in population.
1071 parameters:
1072 return:
1073 last updated: 31/05/01
1074 **********************************************************************/
1075
1076 double ga_population_convergence_genotypes( population *pop )
1077 {
1078 int i, j; /* Loop over pairs of entities. */
1079 int count=0, converged=0; /* Number of comparisons, matches. */
1080
1081 if ( !pop ) die("Null pointer to population structure passed.");
1082 if (pop->size < 1) die("Pointer to empty population structure passed.");
1083
1084 for (i=1; i<pop->size; i++)
1085 {
1086 for (j=0; j<i; j++)
1087 {
1088 if (ga_compare_genome(pop, pop->entity_iarray[i], pop->entity_iarray[j]))
1089 converged++;
1090 count++;
1091 }
1092 }
1093
1094 return (double) converged/count;
1095 }
1096
1097
1098 /**********************************************************************
1099 ga_population_convergence_chromosomes()
1100 synopsis: Determine ratio of converged chromosomes in population.
1101 parameters:
1102 return:
1103 last updated: 31/05/01
1104 **********************************************************************/
1105
1106 double ga_population_convergence_chromosomes( population *pop )
1107 {
1108 int i, j; /* Loop over pairs of entities. */
1109 int k; /* Loop over chromosomes. */
1110 int count=0, converged=0; /* Number of comparisons, matches. */
1111
1112 if ( !pop ) die("Null pointer to population structure passed.");
1113 if (pop->size < 1) die("Pointer to empty population structure passed.");
1114
1115 for (i=1; i<pop->size; i++)
1116 {
1117 for (j=0; j<i; j++)
1118 {
1119 for (k=0; k<pop->num_chromosomes; k++)
1120 {
1121 /* FIXME: Not counted efficiently: */
1122 if (ga_count_match_alleles( pop->len_chromosomes,
1123 pop->entity_iarray[i]->chromosome[k],
1124 pop->entity_iarray[j]->chromosome[k] ) == pop->len_chromosomes)
1125 converged++;
1126 count++;
1127 }
1128 }
1129 }
1130
1131 return (double) converged/count;
1132 }
1133
1134
1135 /**********************************************************************
1136 ga_population_convergence_alleles()
1137 synopsis: Determine ratio of converged alleles in population.
1138 parameters:
1139 return:
1140 last updated: 31/05/01
1141 **********************************************************************/
1142
1143 double ga_population_convergence_alleles( population *pop )
1144 {
1145 int i, j; /* Loop over pairs of entities. */
1146 int k; /* Loop over chromosomes. */
1147 int count=0, converged=0; /* Number of comparisons, matches. */
1148
1149 if ( !pop ) die("Null pointer to population structure passed.");
1150 if (pop->size < 1) die("Pointer to empty population structure passed.");
1151
1152 for (i=1; i<pop->size; i++)
1153 {
1154 for (j=0; j<i; j++)
1155 {
1156 for (k=0; k<pop->num_chromosomes; k++)
1157 {
1158 converged+=ga_count_match_alleles( pop->len_chromosomes,
1159 pop->entity_iarray[i]->chromosome[k],
1160 pop->entity_iarray[j]->chromosome[k] );
1161 count+=pop->len_chromosomes;
1162 }
1163 }
1164 }
1165
1166 return (double) converged/count;
1167 }
1168 #endif
1169
1170
1171 /**********************************************************************
1172 ga_get_entity_rank()
1173 synopsis: Gets an entity's rank (subscript into entity_iarray of
1174 the population). This is not necessarily the fitness
1175 rank unless the population has been sorted.
1176 parameters:
1177 return:
1178 last updated: 22/01/01
1179 **********************************************************************/
1180
ga_get_entity_rank(population * pop,entity * e)1181 int ga_get_entity_rank(population *pop, entity *e)
1182 {
1183 int rank=0; /* The rank. */
1184
1185 while (rank < pop->size)
1186 {
1187 if (pop->entity_iarray[rank] == e) return rank;
1188 rank++;
1189 }
1190
1191 return -1;
1192 }
1193
1194
1195 /**********************************************************************
1196 ga_get_entity_rank_from_id()
1197 synopsis: Gets an entity's rank (subscript into entity_iarray of
1198 the population). This is not necessarily the fitness
1199 rank unless the population has been sorted.
1200 parameters:
1201 return:
1202 last updated: 18 Mar 2002
1203 **********************************************************************/
1204
ga_get_entity_rank_from_id(population * pop,int id)1205 int ga_get_entity_rank_from_id(population *pop, int id)
1206 {
1207 int rank=0; /* The rank. */
1208
1209 while (rank < pop->size)
1210 {
1211 if (pop->entity_iarray[rank] == pop->entity_array[id]) return rank;
1212 rank++;
1213 }
1214
1215 return -1;
1216 }
1217
1218
1219 /**********************************************************************
1220 ga_get_entity_id_from_rank()
1221 synopsis: Gets an entity's id from its rank.
1222 parameters:
1223 return:
1224 last updated: 18 Mar 2002
1225 **********************************************************************/
1226
ga_get_entity_id_from_rank(population * pop,int rank)1227 int ga_get_entity_id_from_rank(population *pop, int rank)
1228 {
1229 int id=0; /* The entity's index. */
1230
1231 while (id < pop->max_size)
1232 {
1233 if (pop->entity_array[id] == pop->entity_iarray[rank]) return id;
1234 id++;
1235 }
1236
1237 return -1;
1238 }
1239
1240
1241 /**********************************************************************
1242 ga_get_entity_id()
1243 synopsis: Gets an entity's internal index.
1244 parameters: population *pop
1245 entity *e
1246 return: entity id
1247 last updated: 18 Mar 2002
1248 **********************************************************************/
1249
ga_get_entity_id(population * pop,entity * e)1250 int ga_get_entity_id(population *pop, entity *e)
1251 {
1252 int id=0; /* The index. */
1253
1254 if ( !pop ) die("Null pointer to population structure passed.");
1255 if ( !e ) die("Null pointer to entity structure passed.");
1256
1257 while (id < pop->max_size)
1258 {
1259 if (pop->entity_array[id] == e) return id;
1260 id++;
1261 }
1262
1263 return -1;
1264 }
1265
1266
1267 /**********************************************************************
1268 ga_get_entity_from_id()
1269 synopsis: Gets a pointer to an entity from it's internal index
1270 (subscript in the entity_array array).
1271 parameters:
1272 return:
1273 last updated: 29 Apr 2002
1274 **********************************************************************/
1275
ga_get_entity_from_id(population * pop,const unsigned int id)1276 entity *ga_get_entity_from_id(population *pop, const unsigned int id)
1277 {
1278 if ( !pop ) die("Null pointer to population structure passed.");
1279
1280 if ( id>pop->max_size ) return NULL;
1281
1282 return pop->entity_array[id];
1283 }
1284
1285
1286 /**********************************************************************
1287 ga_get_entity_from_rank()
1288 synopsis: Gets a pointer to an entity from it's internal rank.
1289 (subscript into the entity_iarray buffer).
1290 Note that this only relates to fitness ranking if
1291 the population has been properly sorted.
1292 parameters:
1293 return:
1294 last updated: 29 Apr 2004
1295 **********************************************************************/
1296
ga_get_entity_from_rank(population * pop,const unsigned int rank)1297 entity *ga_get_entity_from_rank(population *pop, const unsigned int rank)
1298 {
1299 if ( !pop ) die("Null pointer to population structure passed.");
1300
1301 if ( rank>pop->size ) return NULL;
1302
1303 return pop->entity_iarray[rank];
1304 }
1305
1306
1307 /**********************************************************************
1308 ga_entity_setup()
1309 synopsis: Prepares a pre-allocated entity structure for use.
1310 Chromosomes are allocated, but will contain garbage.
1311 parameters:
1312 return:
1313 last updated: 18 Mar 2002
1314 **********************************************************************/
1315
ga_entity_setup(population * pop,entity * joe)1316 static boolean ga_entity_setup(population *pop, entity *joe)
1317 {
1318
1319 if (!joe)
1320 die("Null pointer to entity structure passed.");
1321 if (!pop->chromosome_constructor)
1322 die("Chromosome constructor not defined.");
1323
1324 /* Allocate chromosome structures. */
1325 joe->chromosome = NULL;
1326 pop->chromosome_constructor(pop, joe);
1327
1328 /* Physical characteristics currently undefined. */
1329 joe->data=NULL;
1330
1331 /* No fitness evaluated yet. */
1332 joe->fitness=GA_MIN_FITNESS;
1333
1334 return TRUE;
1335 }
1336
1337
1338 /**********************************************************************
1339 ga_entity_dereference_by_rank()
1340 synopsis: Marks an entity structure as unused.
1341 Deallocation is expensive. It is better to re-use this
1342 memory. So, that is what we do.
1343 Any contents of entities data field are freed.
1344 If rank is known, this is much quicker than the plain
1345 ga_entity_dereference() function.
1346 Note, no error checking in the interests of speed.
1347 parameters:
1348 return:
1349 last updated: 19 Mar 2002
1350 **********************************************************************/
1351
ga_entity_dereference_by_rank(population * pop,int rank)1352 boolean ga_entity_dereference_by_rank(population *pop, int rank)
1353 {
1354 int i; /* Loop variable over the indexed array. */
1355 entity *dying=pop->entity_iarray[rank]; /* Dead entity. */
1356
1357 if (!dying) die("Invalid entity rank");
1358
1359 /* Clear user data. */
1360 if (dying->data)
1361 {
1362 destruct_list(pop, dying->data);
1363 dying->data=NULL;
1364 }
1365
1366 THREAD_LOCK(pop->lock);
1367
1368 /* Population size is one less now! */
1369 pop->size--;
1370
1371 /* Deallocate chromosomes. */
1372 if (dying->chromosome) pop->chromosome_destructor(pop, dying);
1373
1374 /* Update entity_iarray[], so there are no gaps! */
1375 for (i=rank; i<pop->size; i++)
1376 pop->entity_iarray[i] = pop->entity_iarray[i+1];
1377
1378 pop->entity_iarray[pop->size] = NULL;
1379
1380 /* Release index. */
1381 i = ga_get_entity_id(pop, dying);
1382 pop->entity_array[ga_get_entity_id(pop, dying)] = NULL;
1383
1384 THREAD_UNLOCK(pop->lock);
1385
1386 /* Release memory. */
1387 mem_chunk_free(pop->entity_chunk, dying);
1388
1389 /* printf("ENTITY %d DEREFERENCED. New pop size = %d\n", i, pop->size);*/
1390
1391 return TRUE;
1392 }
1393
1394
1395 /**********************************************************************
1396 ga_entity_dereference_by_id()
1397 synopsis: Marks an entity structure as unused.
1398 Deallocation is expensive. It is better to re-use this
1399 memory. So, that is what we do.
1400 Any contents of entities data field are freed.
1401 If rank is known, this is much quicker than the plain
1402 ga_entity_dereference() function, while this index
1403 based version is still almost as fast.
1404 Note, no error checking in the interests of speed.
1405 parameters:
1406 return:
1407 last updated: 19 Mar 2002
1408 **********************************************************************/
1409
ga_entity_dereference_by_id(population * pop,int id)1410 boolean ga_entity_dereference_by_id(population *pop, int id)
1411 {
1412 int i; /* Loop variable over the indexed array. */
1413 entity *dying=pop->entity_array[id]; /* Dead entity. */
1414
1415 if (!dying) die("Invalid entity index");
1416
1417 /* Clear user data. */
1418 if (dying->data)
1419 {
1420 destruct_list(pop, dying->data);
1421 dying->data=NULL;
1422 }
1423
1424 THREAD_LOCK(pop->lock);
1425
1426 /* Population size is one less now! */
1427 pop->size--;
1428
1429 /* Update entity_iarray[], so there are no gaps! */
1430 for (i=ga_get_entity_rank(pop, dying); i<pop->size; i++)
1431 pop->entity_iarray[i] = pop->entity_iarray[i+1];
1432
1433 pop->entity_iarray[pop->size] = NULL;
1434
1435 /* Deallocate chromosomes. */
1436 if (dying->chromosome) pop->chromosome_destructor(pop, dying);
1437
1438 THREAD_UNLOCK(pop->lock);
1439
1440 /* Release index. */
1441 pop->entity_array[id] = NULL;
1442
1443 /* Release memory. */
1444 mem_chunk_free(pop->entity_chunk, dying);
1445
1446 /* printf("ENTITY %d DEREFERENCED. New pop size = %d\n", id, pop->size);*/
1447
1448 return TRUE;
1449 }
1450
1451
1452 /**********************************************************************
1453 ga_entity_dereference()
1454 synopsis: Marks an entity structure as unused.
1455 Deallocation is expensive. It is better to re-use this
1456 memory. So, that is what we do.
1457 Any contents of entities data field are freed.
1458 If rank is known, the above
1459 ga_entity_dereference_by_rank() or
1460 ga_entity_dereference_by_id() functions are much
1461 faster.
1462 parameters:
1463 return:
1464 last updated: 16/03/01
1465 **********************************************************************/
1466
ga_entity_dereference(population * pop,entity * dying)1467 boolean ga_entity_dereference(population *pop, entity *dying)
1468 {
1469 return ga_entity_dereference_by_rank(pop, ga_get_entity_rank(pop, dying));
1470 }
1471
1472
1473 /**********************************************************************
1474 ga_entity_clear_data()
1475 synopsis: Clears some of the entity's data. Safe if data doesn't
1476 exist anyway.
1477 parameters:
1478 return:
1479 last updated: 20/12/00
1480 **********************************************************************/
1481
ga_entity_clear_data(population * p,entity * entity,const int chromosome)1482 void ga_entity_clear_data(population *p, entity *entity, const int chromosome)
1483 {
1484 SLList *tmplist;
1485 vpointer data; /* Data in item. */
1486
1487 if (entity->data)
1488 {
1489 tmplist = slink_nth(entity->data, chromosome);
1490 if ( (data = slink_data(tmplist)) )
1491 {
1492 p->data_destructor(data);
1493 tmplist->data=NULL;
1494 }
1495 }
1496
1497 return;
1498 }
1499
1500
1501 /**********************************************************************
1502 ga_entity_blank()
1503 synopsis: Clears the entity's data.
1504 Equivalent to an optimised ga_entity_dereference()
1505 followed by ga_get_free_entity(). It is much more
1506 preferable to use this fuction!
1507 Chromosomes are gaurenteed to be intact, but may be
1508 overwritten by user.
1509 parameters:
1510 return:
1511 last updated: 18/12/00
1512 **********************************************************************/
1513
ga_entity_blank(population * p,entity * entity)1514 void ga_entity_blank(population *p, entity *entity)
1515 {
1516 if (entity->data)
1517 {
1518 destruct_list(p, entity->data);
1519 entity->data=NULL;
1520 }
1521
1522 entity->fitness=GA_MIN_FITNESS;
1523
1524 /* printf("ENTITY %d CLEARED.\n", ga_get_entity_id(p, entity));*/
1525
1526 return;
1527 }
1528
1529
1530 /**********************************************************************
1531 ga_get_free_entity()
1532 synopsis: Returns pointer to an unused entity structure from the
1533 population's entity pool. Increments population size
1534 too.
1535 parameters: population *pop
1536 return: entity *entity
1537 last updated: 18 Mar 2002
1538 **********************************************************************/
1539
ga_get_free_entity(population * pop)1540 entity *ga_get_free_entity(population *pop)
1541 {
1542 int new_max_size; /* Increased maximum number of entities. */
1543 int i;
1544 entity *fresh; /* Unused entity structure. */
1545
1546 /*
1547 plog(LOG_DEBUG, "Locating free entity structure.");
1548 */
1549 THREAD_LOCK(pop->lock);
1550
1551 /*
1552 * Do we have room for any new structures?
1553 */
1554 if (pop->max_size == (pop->size+1))
1555 { /* No, so allocate some more space. */
1556 plog(LOG_VERBOSE, "No unused entities available -- allocating additional structures.");
1557
1558 new_max_size = (pop->max_size * 3)/2 + 1;
1559 pop->entity_array = s_realloc(pop->entity_array, new_max_size*sizeof(entity*));
1560 pop->entity_iarray = s_realloc(pop->entity_iarray, new_max_size*sizeof(entity*));
1561
1562 for (i=pop->max_size; i<new_max_size; i++)
1563 {
1564 pop->entity_array[i] = NULL;
1565 pop->entity_iarray[i] = NULL;
1566 }
1567
1568 pop->max_size = new_max_size;
1569 pop->free_index = new_max_size-1;
1570 }
1571
1572 /* Find unused entity index. */
1573 while (pop->entity_array[pop->free_index]!=NULL)
1574 {
1575 if (pop->free_index == 0) pop->free_index=pop->max_size;
1576 pop->free_index--;
1577 }
1578
1579 /* Prepare it. */
1580 fresh = (entity *)mem_chunk_alloc(pop->entity_chunk);
1581
1582 pop->entity_array[pop->free_index] = fresh;
1583 ga_entity_setup(pop, fresh);
1584
1585 /* Store in lowest free slot in entity_iarray */
1586 pop->entity_iarray[pop->size] = fresh;
1587
1588 /* Population is bigger now! */
1589 pop->size++;
1590
1591 THREAD_UNLOCK(pop->lock);
1592
1593 /* printf("ENTITY %d ALLOCATED.\n", pop->free_index);*/
1594
1595 return fresh;
1596 }
1597
1598
1599 /**********************************************************************
1600 ga_copy_data()
1601 synopsis: Copy one chromosome's portion of the data field of an
1602 entity structure to another entity structure. (Copies
1603 the portion of the phenome relating to that chromosome)
1604 'Copies' NULL data safely.
1605 The destination chromosomes must be filled in order.
1606 If these entities are in differing populations, no
1607 problems will occur provided that the
1608 data_ref_incrementor callbacks are identical or at least
1609 compatible.
1610 parameters:
1611 return:
1612 last updated: 18/12/00
1613 **********************************************************************/
1614
ga_copy_data(population * pop,entity * dest,entity * src,const int chromosome)1615 boolean ga_copy_data(population *pop, entity *dest, entity *src, const int chromosome)
1616 {
1617 vpointer tmpdata=NULL; /* Temporary pointer. */
1618
1619 if ( !src || !(tmpdata = slink_nth_data(src->data, chromosome)) )
1620 {
1621 dest->data = slink_append(dest->data, NULL);
1622 }
1623 else
1624 {
1625 dest->data = slink_append(dest->data, tmpdata);
1626 pop->data_ref_incrementor(tmpdata);
1627 }
1628
1629 return TRUE;
1630 }
1631
1632
1633 /**********************************************************************
1634 ga_copy_chromosome()
1635 synopsis: Copy one chromosome between entities.
1636 If these entities are in differing populations, no
1637 problems will occur provided that the chromosome
1638 datatypes match up.
1639 parameters:
1640 return:
1641 last updated: 18/12/00
1642 **********************************************************************/
1643
ga_copy_chromosome(population * pop,entity * dest,entity * src,const int chromosome)1644 static boolean ga_copy_chromosome( population *pop, entity *dest, entity *src,
1645 const int chromosome )
1646 {
1647
1648 pop->chromosome_replicate(pop, src, dest, chromosome);
1649
1650 return TRUE;
1651 }
1652
1653
1654 /**********************************************************************
1655 ga_entity_copy_all_chromosomes()
1656 synopsis: Copy genetic data between entity structures.
1657 If these entities are in differing populations, no
1658 problems will occur provided that the chromosome
1659 properties are identical.
1660 parameters:
1661 return:
1662 last updated: 20/12/00
1663 **********************************************************************/
1664
ga_entity_copy_all_chromosomes(population * pop,entity * dest,entity * src)1665 boolean ga_entity_copy_all_chromosomes(population *pop, entity *dest, entity *src)
1666 {
1667 int i; /* Loop variable over all chromosomes. */
1668
1669 /* Checks */
1670 if (!dest || !src) die("Null pointer to entity structure passed");
1671
1672 /*
1673 * Ensure destination structure is not likely be already in use.
1674 */
1675 if (dest->data) die("Why does this entity already contain data?");
1676
1677 /*
1678 * Copy genetic data.
1679 */
1680 for (i=0; i<pop->num_chromosomes; i++)
1681 {
1682 ga_copy_data(pop, dest, src, i); /* Phenome. */
1683 ga_copy_chromosome(pop, dest, src, i); /* Genome. */
1684 }
1685
1686 return TRUE;
1687 }
1688
1689
1690 /**********************************************************************
1691 ga_entity_copy_chromosome()
1692 synopsis: Copy chromosome and user data between entity
1693 structures.
1694 parameters:
1695 return:
1696 last updated: 22/01/01
1697 **********************************************************************/
1698
ga_entity_copy_chromosome(population * pop,entity * dest,entity * src,int chromo)1699 boolean ga_entity_copy_chromosome(population *pop, entity *dest, entity *src, int chromo)
1700 {
1701
1702 /* Checks. */
1703 if (!dest || !src) die("Null pointer to entity structure passed");
1704 if (chromo<0 || chromo>=pop->num_chromosomes) die("Invalid chromosome number.");
1705
1706 /*
1707 * Ensure destination structure is not likely be already in use.
1708 */
1709 if (dest->data) die("Why does this entity already contain data?");
1710
1711 /*
1712 * Copy genetic and associated structural data (phenomic data).
1713 */
1714 /*
1715 memcpy(dest->chromosome[chromo], src->chromosome[chromo],
1716 pop->len_chromosomes*sizeof(int));
1717 */
1718 ga_copy_data(pop, dest, src, chromo);
1719 ga_copy_chromosome(pop, dest, src, chromo);
1720
1721 return TRUE;
1722 }
1723
1724
1725 /**********************************************************************
1726 ga_entity_copy()
1727 synopsis: Copy entire entity structure. This is safe
1728 for copying between populations... provided that they
1729 are compatible.
1730 parameters:
1731 return:
1732 last updated: 22/01/01
1733 **********************************************************************/
1734
ga_entity_copy(population * pop,entity * dest,entity * src)1735 boolean ga_entity_copy(population *pop, entity *dest, entity *src)
1736 {
1737
1738 ga_entity_copy_all_chromosomes(pop, dest, src);
1739 dest->fitness = src->fitness;
1740
1741 return TRUE;
1742 }
1743
1744
1745 /**********************************************************************
1746 ga_entity_clone()
1747 synopsis: Clone an entity structure.
1748 Safe for cloning into a different population, provided
1749 that the populations are compatible.
1750 parameters: population *pop Population.
1751 entity *parent The original entity.
1752 return: entity *dolly The new entity.
1753 last updated: 07/07/01
1754 **********************************************************************/
1755
ga_entity_clone(population * pop,entity * parent)1756 entity *ga_entity_clone(population *pop, entity *parent)
1757 {
1758 entity *dolly; /* The clone. */
1759
1760 dolly = ga_get_free_entity(pop);
1761
1762 ga_entity_copy_all_chromosomes(pop, dolly, parent);
1763 dolly->fitness = parent->fitness;
1764
1765 return dolly;
1766 }
1767
1768
1769 /**********************************************************************
1770 Network communication (population/entity migration) functions.
1771 **********************************************************************/
1772
1773 #if W32_CRIPPLED != 1 && HAVE_MPI == 1
1774
1775 /*
1776 * Convenience wrapper around MPI_COmm_rank().
1777 */
mpi_get_rank(void)1778 static int mpi_get_rank(void)
1779 {
1780 int rank;
1781
1782 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
1783
1784 return rank;
1785 }
1786
1787
1788 /*
1789 * Convenience wrapper around MPI_Recv().
1790 */
mpi_receive(void * buf,const int count,const MPI_Datatype type,const int node,const int tag)1791 static boolean mpi_receive(void *buf, const int count,
1792 const MPI_Datatype type, const int node,
1793 const int tag)
1794 {
1795 MPI_Status status; /* MPI status struct. */
1796
1797 /* Checks */
1798 if (!buf) die("Null pointer to (void *) buffer passed.");
1799 if (mpi_get_rank()==node) die("Why should I send a message to myself?");
1800
1801 MPI_Recv( buf, count, type, node, tag, MPI_COMM_WORLD, &status );
1802
1803 /* FIXME: Should check the status structure here! */
1804
1805 return TRUE;
1806 }
1807
1808
1809 /**********************************************************************
1810 ga_population_send_by_mask()
1811 synopsis: Send selected entities from a population to another
1812 processor. Only fitness and chromosomes sent.
1813 parameters:
1814 return:
1815 last updated: 31 Jan 2002
1816 **********************************************************************/
1817
ga_population_send_by_mask(population * pop,int dest_node,int num_to_send,boolean * send_mask)1818 void ga_population_send_by_mask( population *pop, int dest_node, int num_to_send, boolean *send_mask )
1819 {
1820 int i;
1821 int count=0;
1822 int len=0; /* Length of buffer to send. */
1823 unsigned int max_len=0;
1824 byte *buffer=NULL;
1825
1826 /*
1827 * Send number of entities.
1828 */
1829 MPI_Send(&num_to_send, 1, MPI_INT, dest_node, GA_TAG_NUMENTITIES, MPI_COMM_WORLD);
1830
1831 /*
1832 * Slight knudge to determine length of buffer. Should have a more
1833 * elegant approach for this.
1834 * Sending this length here should not be required at all.
1835 */
1836 len = (int) pop->chromosome_to_bytes(pop, pop->entity_iarray[0], &buffer, &max_len);
1837 MPI_Send(&len, 1, MPI_INT, dest_node, GA_TAG_ENTITYLEN, MPI_COMM_WORLD);
1838
1839 /*
1840 printf("DEBUG: Node %d sending %d entities of length %d to %d\n",
1841 mpi_get_rank(), num_to_send, len, dest_node);
1842 */
1843
1844 /*
1845 * Send required entities individually.
1846 */
1847 for (i=0; i<pop->size && count<num_to_send; i++)
1848 {
1849 if (send_mask[i])
1850 {
1851 /* printf("DEBUG: Node %d sending entity %d/%d (%d/%d) with fitness %f\n",
1852 mpi_get_rank(), count, num_to_send, i, pop->size, pop->entity_iarray[i]->fitness); */
1853 MPI_Send(&(pop->entity_iarray[i]->fitness), 1, MPI_DOUBLE, dest_node, GA_TAG_ENTITYFITNESS, MPI_COMM_WORLD);
1854 if (len != (int) pop->chromosome_to_bytes(pop, pop->entity_iarray[i], &buffer, &max_len))
1855 die("Internal length mismatch");
1856 MPI_Send(buffer, len, MPI_BYTE, dest_node, GA_TAG_ENTITYCHROMOSOME, MPI_COMM_WORLD);
1857 count++;
1858 }
1859 }
1860
1861 if (count != num_to_send)
1862 die("Incorrect value for num_to_send");
1863
1864 /*
1865 * We only need to deallocate the buffer if it was allocated (i.e. if
1866 * the "chromosome_to_bytes" callback set max_len).
1867 */
1868 if (max_len!=0) s_free(buffer);
1869
1870 /* printf("DEBUG: Node %d finished sending\n", mpi_get_rank());*/
1871
1872 return;
1873 }
1874
1875
1876 /**********************************************************************
1877 ga_population_send_every()
1878 synopsis: Send all entities from a population to another
1879 processor. Only fitness and chromosomes sent.
1880 parameters:
1881 return:
1882 last updated: 31 Jan 2002
1883 **********************************************************************/
1884
ga_population_send_every(population * pop,int dest_node)1885 void ga_population_send_every( population *pop, int dest_node )
1886 {
1887 int i;
1888 int len; /* Length of buffer to send. */
1889 unsigned int max_len=0; /* Maximum length of buffer. */
1890 byte *buffer=NULL;
1891
1892 if ( !pop ) die("Null pointer to population structure passed.");
1893
1894 /*
1895 * Send number of entities.
1896 */
1897 MPI_Send(&(pop->size), 1, MPI_INT, dest_node, GA_TAG_NUMENTITIES, MPI_COMM_WORLD);
1898
1899 /*
1900 * Slight kludge to determine length of buffer. Should have a more
1901 * elegant approach for this.
1902 * Sending this length here should not be required at all.
1903 */
1904 len = (int) pop->chromosome_to_bytes(pop, pop->entity_iarray[0], &buffer, &max_len);
1905 MPI_Send(&len, 1, MPI_INT, dest_node, GA_TAG_ENTITYLEN, MPI_COMM_WORLD);
1906
1907 /*
1908 * Send all entities individually.
1909 */
1910 for (i=0; i<pop->size; i++)
1911 {
1912 MPI_Send(&(pop->entity_iarray[i]->fitness), 1, MPI_DOUBLE, dest_node, GA_TAG_ENTITYFITNESS, MPI_COMM_WORLD);
1913 if (len != (int) pop->chromosome_to_bytes(pop, pop->entity_iarray[i], &buffer, &max_len))
1914 die("Internal length mismatch");
1915 MPI_Send(buffer, len, MPI_BYTE, dest_node, GA_TAG_ENTITYCHROMOSOME, MPI_COMM_WORLD);
1916 }
1917
1918 /*
1919 * We only need to deallocate the buffer if it was allocated (i.e. if
1920 * the "chromosome_to_bytes" callback set max_len).
1921 */
1922 if (max_len!=0) s_free(buffer);
1923
1924 return;
1925 }
1926
1927
1928 /**********************************************************************
1929 ga_population_append_receive()
1930 synopsis: Recieve a set of entities from a population on another
1931 processor and append them to a current population.
1932 Only fitness and chromosomes received.
1933 parameters:
1934 return:
1935 last updated: 31 Jan 2002
1936 **********************************************************************/
1937
ga_population_append_receive(population * pop,int src_node)1938 void ga_population_append_receive( population *pop, int src_node )
1939 {
1940 int i;
1941 int len=0; /* Length of buffer to receive. */
1942 byte *buffer; /* Receive buffer. */
1943 int num_to_recv; /* Number of entities to receive. */
1944 entity *entity; /* New entity. */
1945
1946 if ( !pop ) die("Null pointer to population structure passed.");
1947
1948 /*
1949 * Get number of entities to receive and the length of each.
1950 * FIXME: This length data shouldn't be needed!
1951 */
1952 mpi_receive(&num_to_recv, 1, MPI_INT, src_node, GA_TAG_NUMENTITIES);
1953 mpi_receive(&len, 1, MPI_INT, src_node, GA_TAG_ENTITYLEN);
1954
1955 /*
1956 printf("DEBUG: Node %d anticipating %d entities of length %d from %d\n",
1957 mpi_get_rank(), num_to_recv, len, src_node);
1958 */
1959
1960 if (num_to_recv>0)
1961 {
1962 buffer = s_malloc(len*sizeof(byte));
1963
1964 /*
1965 * Receive all entities individually.
1966 */
1967 for (i=0; i<num_to_recv; i++)
1968 {
1969 entity = ga_get_free_entity(pop);
1970 mpi_receive(&(entity->fitness), 1, MPI_DOUBLE, src_node, GA_TAG_ENTITYFITNESS);
1971 mpi_receive(buffer, len, MPI_BYTE, src_node, GA_TAG_ENTITYCHROMOSOME);
1972 pop->chromosome_from_bytes(pop, entity, buffer);
1973 /* printf("DEBUG: Node %d received entity %d/%d (%d) with fitness %f\n",
1974 mpi_get_rank(), i, num_to_recv, pop->size, entity->fitness);
1975 */
1976 }
1977
1978 s_free(buffer);
1979 }
1980
1981 /* printf("DEBUG: Node %d finished receiving\n", mpi_get_rank());*/
1982
1983 return;
1984 }
1985
1986
1987 /**********************************************************************
1988 ga_population_new_receive()
1989 synopsis: Recieve a population structure (excluding actual
1990 entities) from another processor.
1991 Note that the callbacks wiil need to be subsequently
1992 defined by the user.
1993 parameters:
1994 return:
1995 last updated: 16 Feb 2005
1996 **********************************************************************/
1997
ga_population_new_receive(int src_node)1998 population *ga_population_new_receive( int src_node )
1999 {
2000 population *pop=NULL;
2001
2002 plog(LOG_FIXME, "Function not fully implemented");
2003
2004 mpi_receive(&(pop->stable_size), 1, MPI_INT, src_node, GA_TAG_POPSTABLESIZE);
2005 mpi_receive(&(pop->crossover_ratio), 1, MPI_DOUBLE, src_node, GA_TAG_POPCROSSOVER);
2006 mpi_receive(&(pop->mutation_ratio), 1, MPI_DOUBLE, src_node, GA_TAG_POPMUTATION);
2007 mpi_receive(&(pop->migration_ratio), 1, MPI_DOUBLE, src_node, GA_TAG_POPMIGRATION);
2008 mpi_receive(&(pop->allele_mutation_prob), 1, MPI_DOUBLE, src_node, GA_TAG_POPALLELEMUTPROB);
2009 mpi_receive(&(pop->allele_min_integer), 1, MPI_INT, src_node, GA_TAG_POPALLELEMININT);
2010 mpi_receive(&(pop->allele_max_integer), 1, MPI_INT, src_node, GA_TAG_POPALLELEMAXINT);
2011 mpi_receive(&(pop->allele_min_double), 1, MPI_DOUBLE, src_node, GA_TAG_POPALLELEMINDOUBLE);
2012 mpi_receive(&(pop->allele_max_double), 1, MPI_DOUBLE, src_node, GA_TAG_POPALLELEMAXDOUBLE);
2013
2014 return pop;
2015 }
2016
2017
2018 /**********************************************************************
2019 ga_population_receive()
2020 synopsis: Recieve a population structure (including actual
2021 entities) from another processor.
2022 parameters:
2023 return:
2024 last updated: 24 Jan 2002
2025 **********************************************************************/
2026
ga_population_receive(int src_node)2027 population *ga_population_receive( int src_node )
2028 {
2029 population *pop;
2030
2031 pop = ga_population_new_receive( src_node );
2032 ga_population_append_receive( pop, src_node );
2033
2034 return pop;
2035 }
2036
2037
2038 /**********************************************************************
2039 ga_population_send()
2040 synopsis: Send population structure (excluding actual entities)
2041 to another processor.
2042 It should be noted that neither the userdata nor the
2043 function definitions will be sent.
2044 Some other less useful data is also not transfered.
2045 parameters:
2046 return:
2047 last updated: 16 Feb 2005
2048 **********************************************************************/
2049
ga_population_send(population * pop,int dest_node)2050 void ga_population_send( population *pop, int dest_node )
2051 {
2052
2053 if ( !pop ) die("Null pointer to population structure passed.");
2054
2055 MPI_Send(&(pop->stable_size), 1, MPI_INT, dest_node, GA_TAG_POPSTABLESIZE, MPI_COMM_WORLD);
2056 MPI_Send(&(pop->crossover_ratio), 1, MPI_DOUBLE, dest_node, GA_TAG_POPCROSSOVER, MPI_COMM_WORLD);
2057 MPI_Send(&(pop->mutation_ratio), 1, MPI_DOUBLE, dest_node, GA_TAG_POPMUTATION, MPI_COMM_WORLD);
2058 MPI_Send(&(pop->migration_ratio), 1, MPI_DOUBLE, dest_node, GA_TAG_POPMIGRATION, MPI_COMM_WORLD);
2059 MPI_Send(&(pop->allele_mutation_prob), 1, MPI_DOUBLE, dest_node, GA_TAG_POPALLELEMUTPROB, MPI_COMM_WORLD);
2060 MPI_Send(&(pop->allele_min_integer), 1, MPI_INT, dest_node, GA_TAG_POPALLELEMININT, MPI_COMM_WORLD);
2061 MPI_Send(&(pop->allele_max_integer), 1, MPI_INT, dest_node, GA_TAG_POPALLELEMAXINT, MPI_COMM_WORLD);
2062 MPI_Send(&(pop->allele_min_double), 1, MPI_DOUBLE, dest_node, GA_TAG_POPALLELEMINDOUBLE, MPI_COMM_WORLD);
2063 MPI_Send(&(pop->allele_max_double), 1, MPI_DOUBLE, dest_node, GA_TAG_POPALLELEMAXDOUBLE, MPI_COMM_WORLD);
2064
2065 return;
2066 }
2067
2068
2069 /**********************************************************************
2070 ga_population_send_all()
2071 synopsis: Send population structure (including all entities)
2072 to another processor.
2073 parameters:
2074 return:
2075 last updated: 24 Jan 2002
2076 **********************************************************************/
2077
ga_population_send_all(population * pop,int dest_node)2078 void ga_population_send_all( population *pop, int dest_node )
2079 {
2080
2081 /* Note that checks are performed in the two called functions. */
2082
2083 ga_population_send(pop, dest_node);
2084 ga_population_send_every(pop, dest_node);
2085
2086 return;
2087 }
2088
2089
2090 #if 0
2091 /**********************************************************************
2092 ga_marktosend_entity()
2093 synopsis: Mark an entity to be sent to another subpopulation
2094 (i.e. jump to another processor).
2095 parameters:
2096 return:
2097 last updated: 22/09/00
2098 **********************************************************************/
2099
2100 void ga_marktosend_entity(int *send_mask)
2101 {
2102 }
2103 #endif
2104
2105
2106 #if 0
2107 /**********************************************************************
2108 ga_multiproc_compare_entities()
2109 synopsis: Synchronise processors and if appropriate transfer
2110 better solution to this processor.
2111 local will contain the optimum solution from local
2112 and localnew on all processors.
2113 parameters:
2114 return:
2115 last updated: 18/12/00
2116 **********************************************************************/
2117
2118 entity *ga_multiproc_compare_entities( population *pop, entity *localnew, entity *local )
2119 {
2120 double global_max; /* Maximum value across all nodes. */
2121 int maxnode; /* Node with maximum value. */
2122 int *buffer=NULL; /* Send/receive buffer. */
2123 int *buffer_ptr=NULL; /* Current position in end/receive buffer. */
2124 int buffer_size; /* Size of buffer. */
2125 int j; /* Loop over chromosomes. */
2126 entity *tmpentity; /* Entity ptr for swapping. */
2127
2128 plog(LOG_FIXME, "Warning... untested code.");
2129
2130 maxnode = mpi_find_global_max(MAX(localnew->fitness, local->fitness), &global_max);
2131
2132 buffer_size = pop->num_chromosomes*pop->len_chromosomes;
2133 buffer_ptr = buffer = s_malloc(buffer_size*sizeof(int));
2134
2135 if (maxnode == mpi_get_rank())
2136 {
2137 if (localnew->fitness > local->fitness)
2138 {
2139 tmpentity = local;
2140 local = localnew;
2141 localnew = tmpentity;
2142 }
2143
2144 for (j=0; j<pop->num_chromosomes; j++)
2145 {
2146 memcpy(buffer_ptr, local->chromosome[j], pop->len_chromosomes*sizeof(int));
2147 buffer_ptr += pop->len_chromosomes;
2148 }
2149
2150 mpi_distribute( buffer, buffer_size, MPI_INT, maxnode, GA_TAG_BESTSYNC );
2151 }
2152 else
2153 {
2154 mpi_distribute( buffer, buffer_size, MPI_INT, maxnode, GA_TAG_BESTSYNC );
2155
2156 for (j=0; j<pop->num_chromosomes; j++)
2157 {
2158 memcpy(local->chromosome[j], buffer_ptr, pop->len_chromosomes*sizeof(int));
2159 buffer_ptr += pop->len_chromosomes;
2160 }
2161
2162 pop->evaluate(pop, local);
2163 if (local->fitness != global_max)
2164 dief("Best scores don't match %f %f.", local->fitness, global_max);
2165 }
2166
2167 s_free(buffer);
2168
2169 return local;
2170 }
2171
2172
2173 /**********************************************************************
2174 ga_sendrecv_entities()
2175 synopsis: Make entities change subpopulations based on the
2176 previously set mask. (i.e. entities jump to
2177 another processor).
2178 Currently only sends the genetic data and rebuilds the
2179 structure.
2180 FIXME: Send structural data too.
2181 (This functionality should be provided by a user
2182 specified callback.)
2183 parameters:
2184 return:
2185 last updated: 22/09/00
2186 **********************************************************************/
2187
2188 boolean ga_sendrecv_entities( population *pop, int *send_mask, int send_count )
2189 {
2190 int i, j; /* Loop over all chromosomes in all entities. */
2191 int next, prev; /* Processor to send/receive entities with. */
2192 int *buffer=NULL; /* Send/receive buffer. */
2193 int *buffer_ptr=NULL; /* Current position in end/receive buffer. */
2194 int recv_count; /* Number of entities to receive. */
2195 int recv_size, send_size=0; /* Size of buffer. */
2196 int index=0; /* Index of entity to send. */
2197 entity *immigrant; /* New entity. */
2198
2199 plog(LOG_FIXME, "Warning... untested code.");
2200
2201 /* Checks */
2202 if ( !pop ) die("Null pointer to population structure passed.");
2203 if ( !send_mask ) die("Null pointer to int array.");
2204
2205 next = mpi_get_next_rank();
2206 prev = mpi_get_prev_rank();
2207
2208 /* Pack chromosomes into buffer. */
2209 if (send_count > 0)
2210 {
2211 send_size = send_count*pop->num_chromosomes*pop->len_chromosomes;
2212 if ( !(buffer=s_malloc(send_size*sizeof(int))) )
2213 die("Unable to allocate memory.");
2214
2215 buffer_ptr = buffer;
2216
2217 for (i=0; i<send_count; i++)
2218 {
2219 while ( *send_mask == 0 )
2220 { /* Skipping structure. */
2221 send_mask++;
2222 index++;
2223 }
2224
2225 for (j=0; j<pop->num_chromosomes; j++)
2226 {
2227 memcpy(buffer_ptr,
2228 pop->entity_iarray[index]->chromosome[j],
2229 pop->len_chromosomes*sizeof(int));
2230 buffer_ptr += pop->len_chromosomes;
2231 }
2232
2233 send_mask++; /* Ready for next loop */
2234 index++;
2235 }
2236 }
2237
2238 /* Send data to next node. */
2239 plog(LOG_DEBUG, "Sending %d to node %d.", send_count, next);
2240 MPI_Send( &send_count, 1, MPI_INT, next, GA_TAG_MIGRATIONINFO, MPI_COMM_WORLD );
2241
2242 if (send_count > 0)
2243 {
2244 plog(LOG_DEBUG, "Sending %d ints to node %d.", send_size, next);
2245 MPI_Send( buffer, send_size, MPI_INT, next, GA_TAG_MIGRATIONDATA, MPI_COMM_WORLD );
2246 }
2247
2248 /*
2249 helga_start_timer();
2250 */
2251
2252 /* Recieve data from previous node. */
2253 plog(LOG_DEBUG, "Recieving messages from node %d.", prev);
2254
2255 mpi_receive( &recv_count, 1, MPI_INT, prev, GA_TAG_MIGRATIONINFO );
2256
2257 plog(LOG_DEBUG, "Will be receiving %d entities = %d ints (%Zd bytes).",
2258 recv_count,
2259 recv_count*pop->num_chromosomes*pop->len_chromosomes,
2260 recv_count*pop->num_chromosomes*pop->len_chromosomes*sizeof(int));
2261
2262 if (recv_count > 0)
2263 {
2264 recv_size = recv_count*pop->num_chromosomes*pop->len_chromosomes;
2265 if ( !(buffer=s_realloc(buffer, recv_size*sizeof(int))) )
2266 die("Unable to reallocate memory.");
2267
2268 buffer_ptr = buffer;
2269
2270 mpi_receive( buffer, recv_size, MPI_INT, prev, GA_TAG_MIGRATIONDATA );
2271
2272 for (i=0; i<recv_count; i++)
2273 {
2274 immigrant = ga_get_free_entity(pop);
2275 for (j=0; j<pop->num_chromosomes; j++)
2276 {
2277 memcpy(buffer_ptr,
2278 immigrant->chromosome[j],
2279 pop->len_chromosomes*sizeof(int));
2280 buffer_ptr += pop->len_chromosomes;
2281 }
2282 pop->evaluate(pop, immigrant);
2283
2284 /*
2285 plog(LOG_VERBOSE, "Immigrant has fitness %f", immigrant->fitness);
2286 */
2287 }
2288 }
2289
2290 /* How much time did we waste? */
2291 /*
2292 helga_check_timer();
2293 */
2294
2295 if (buffer) s_free(buffer);
2296
2297 return TRUE;
2298 }
2299 #endif
2300 #endif
2301
2302
2303 /**********************************************************************
2304 Environmental operator function.
2305 **********************************************************************/
2306
2307 /**********************************************************************
2308 ga_optimise_entity()
2309 synopsis: Optimise the entity's structure through local
2310 searching in the gene space.
2311 Should be default choice for "adaptation" function.
2312 The original entity will be left untouched.
2313 parameters:
2314 return:
2315 last updated: 24 Oct 2002
2316 **********************************************************************/
2317
ga_optimise_entity(population * pop,entity * unopt)2318 entity *ga_optimise_entity(population *pop, entity *unopt)
2319 {
2320 entity *optimised;
2321
2322 /* Checks */
2323 if ( !pop ) die("Null pointer to population structure passed.");
2324 if ( !unopt ) die("Null pointer to entity structure passed.");
2325
2326 plog(LOG_FIXME,
2327 "This function is deprecated and shoulf not be used.");
2328
2329 optimised = ga_entity_clone(pop, unopt);
2330
2331 /* FIXME: hard-coded value. */
2332 ga_random_ascent_hillclimbing( pop, optimised, 25 );
2333
2334 plog(LOG_DEBUG,
2335 "Entity optimised from %f to %f.",
2336 unopt->fitness, optimised->fitness);
2337
2338 return optimised;
2339 }
2340
2341
2342 /**********************************************************************
2343 GA functions.
2344 **********************************************************************/
2345
2346 /**********************************************************************
2347 ga_population_set_parameters()
2348 synopsis: Sets the GA parameters for a population.
2349 parameters:
2350 return:
2351 last updated: 10 Jun 2002
2352 **********************************************************************/
2353
ga_population_set_parameters(population * pop,const ga_scheme_type scheme,const ga_elitism_type elitism,const double crossover,const double mutation,const double migration)2354 void ga_population_set_parameters( population *pop,
2355 const ga_scheme_type scheme,
2356 const ga_elitism_type elitism,
2357 const double crossover,
2358 const double mutation,
2359 const double migration)
2360 {
2361
2362 if ( !pop ) die("Null pointer to population structure passed.");
2363
2364 plog( LOG_VERBOSE,
2365 "Population's parameters: scheme = %d elitism = %d crossover = %f mutation = %f migration = %f",
2366 (int) scheme, (int) elitism,
2367 crossover, mutation, migration );
2368
2369 pop->scheme = scheme;
2370 pop->elitism = elitism;
2371 pop->crossover_ratio = crossover;
2372 pop->mutation_ratio = mutation;
2373 pop->migration_ratio = migration;
2374
2375 return;
2376 }
2377
2378
2379 /**********************************************************************
2380 ga_population_set_scheme()
2381 synopsis: Sets the evolutionary class for a population.
2382 parameters:
2383 return:
2384 last updated: 10 Jun 2002
2385 **********************************************************************/
2386
ga_population_set_scheme(population * pop,const ga_scheme_type scheme)2387 void ga_population_set_scheme( population *pop,
2388 const ga_scheme_type scheme)
2389 {
2390
2391 if ( !pop ) die("Null pointer to population structure passed.");
2392
2393 plog( LOG_VERBOSE, "Population's evolutionary class = %d", (int) scheme);
2394
2395 pop->scheme = scheme;
2396
2397 return;
2398 }
2399
2400
2401 /**********************************************************************
2402 ga_population_set_elitism()
2403 synopsis: Sets the elitism mode for a population.
2404 parameters:
2405 return:
2406 last updated: 10 Jun 2002
2407 **********************************************************************/
2408
ga_population_set_elitism(population * pop,const ga_elitism_type elitism)2409 void ga_population_set_elitism( population *pop,
2410 const ga_elitism_type elitism)
2411 {
2412
2413 if ( !pop ) die("Null pointer to population structure passed.");
2414
2415 plog( LOG_VERBOSE, "Population's elitism mode = %d", (int) elitism);
2416
2417 pop->elitism = elitism;
2418
2419 return;
2420 }
2421
2422
2423 /**********************************************************************
2424 ga_population_set_mutation()
2425 synopsis: Sets the mutation rate for a population.
2426 parameters:
2427 return:
2428 last updated: 10 Jun 2002
2429 **********************************************************************/
2430
ga_population_set_mutation(population * pop,const double mutation)2431 void ga_population_set_mutation( population *pop,
2432 const double mutation)
2433 {
2434
2435 if ( !pop ) die("Null pointer to population structure passed.");
2436
2437 plog( LOG_VERBOSE, "Population's mutation rate = %f", mutation);
2438
2439 pop->mutation_ratio = mutation;
2440
2441 return;
2442 }
2443
2444
2445 /**********************************************************************
2446 ga_population_set_migration()
2447 synopsis: Sets the migration rate for a population.
2448 parameters:
2449 return:
2450 last updated: 10 Jun 2002
2451 **********************************************************************/
2452
ga_population_set_migration(population * pop,const double migration)2453 void ga_population_set_migration( population *pop,
2454 const double migration)
2455 {
2456
2457 if ( !pop ) die("Null pointer to population structure passed.");
2458
2459 plog( LOG_VERBOSE, "Population's migration rate = %f", migration);
2460
2461 pop->migration_ratio = migration;
2462
2463 return;
2464 }
2465
2466
2467 /**********************************************************************
2468 ga_population_set_crossover()
2469 synopsis: Sets the crossover rate for a population.
2470 parameters:
2471 return:
2472 last updated: 10 Jun 2002
2473 **********************************************************************/
2474
ga_population_set_crossover(population * pop,const double crossover)2475 void ga_population_set_crossover( population *pop,
2476 const double crossover)
2477 {
2478
2479 if ( !pop ) die("Null pointer to population structure passed.");
2480
2481 plog( LOG_VERBOSE, "Population's crossover rate = %f", crossover);
2482
2483 pop->crossover_ratio = crossover;
2484
2485 return;
2486 }
2487
2488
2489 /**********************************************************************
2490 ga_population_set_allele_mutation_prob()
2491 synopsis: Sets the allele mutation rate (e.g. bitwise mutation
2492 probability) for a population.
2493 parameters:
2494 return:
2495 last updated: 16 Feb 2005
2496 **********************************************************************/
2497
ga_population_set_allele_mutation_prob(population * pop,const double prob)2498 void ga_population_set_allele_mutation_prob( population *pop,
2499 const double prob)
2500 {
2501
2502 if ( !pop ) die("Null pointer to population structure passed.");
2503
2504 plog( LOG_VERBOSE, "Population's allele mutation probability = %f", prob);
2505
2506 pop->allele_mutation_prob = prob;
2507
2508 return;
2509 }
2510
2511
2512 /**********************************************************************
2513 ga_population_set_allele_min_integer()
2514 synopsis: Sets the minimum value for an integer allele for a
2515 population.
2516 parameters:
2517 return:
2518 last updated: 17 Feb 2005
2519 **********************************************************************/
2520
ga_population_set_allele_min_integer(population * pop,const int value)2521 void ga_population_set_allele_min_integer( population *pop,
2522 const int value)
2523 {
2524
2525 if ( !pop ) die("Null pointer to population structure passed.");
2526
2527 plog( LOG_VERBOSE, "Population's minimum integer allele value = %d", value);
2528
2529 pop->allele_min_integer = value;
2530
2531 return;
2532 }
2533
2534
2535 /**********************************************************************
2536 ga_population_set_allele_max_integer()
2537 synopsis: Sets the maximum value for an integer allele for a
2538 population.
2539 parameters:
2540 return:
2541 last updated: 17 Feb 2005
2542 **********************************************************************/
2543
ga_population_set_allele_max_integer(population * pop,const int value)2544 void ga_population_set_allele_max_integer( population *pop,
2545 const int value)
2546 {
2547
2548 if ( !pop ) die("Null pointer to population structure passed.");
2549
2550 plog( LOG_VERBOSE, "Population's maximum integer allele value = %d", value);
2551
2552 pop->allele_max_integer = value;
2553
2554 return;
2555 }
2556
2557
2558 /**********************************************************************
2559 ga_population_set_allele_min_double()
2560 synopsis: Sets the minimum value for a double-precision allele
2561 for a population.
2562 parameters:
2563 return:
2564 last updated: 17 Feb 2005
2565 **********************************************************************/
2566
ga_population_set_allele_min_double(population * pop,const double value)2567 void ga_population_set_allele_min_double( population *pop,
2568 const double value)
2569 {
2570
2571 if ( !pop ) die("Null pointer to population structure passed.");
2572
2573 plog( LOG_VERBOSE, "Population's minimum double allele value = %f", value);
2574
2575 pop->allele_min_double = value;
2576
2577 return;
2578 }
2579
2580
2581 /**********************************************************************
2582 ga_population_set_allele_max_double()
2583 synopsis: Sets the maximum value for a doubleprecision allele
2584 for a population.
2585 parameters:
2586 return:
2587 last updated: 17 Feb 2005
2588 **********************************************************************/
2589
ga_population_set_allele_max_double(population * pop,const double value)2590 void ga_population_set_allele_max_double( population *pop,
2591 const double value)
2592 {
2593
2594 if ( !pop ) die("Null pointer to population structure passed.");
2595
2596 plog( LOG_VERBOSE, "Population's maximum double allele value = %f", value);
2597
2598 pop->allele_max_double = value;
2599
2600 return;
2601 }
2602
2603
2604 /**********************************************************************
2605 ga_transcend()
2606 synopsis: Return a population structure to user for analysis or
2607 whatever. But remove it from the population table.
2608 (Like ga_extinction, except doesn't purge memory.)
2609 parameters: unsigned int population id
2610 return: population * population pointer (or NULL)
2611 last updated: 15 Aug 2002
2612 **********************************************************************/
2613
ga_transcend(unsigned int id)2614 population *ga_transcend(unsigned int id)
2615 {
2616 population *pop=NULL; /* Transcending population. */
2617
2618 plog(LOG_VERBOSE, "This population has achieved transcendance!");
2619
2620 THREAD_LOCK(pop_table_lock);
2621 if (pop_table)
2622 {
2623 pop = (population *) table_remove_index(pop_table, id);
2624 if (table_count_items(pop_table) < 1)
2625 {
2626 table_destroy(pop_table);
2627 pop_table=NULL;
2628 }
2629 }
2630 THREAD_UNLOCK(pop_table_lock);
2631
2632 return pop;
2633 }
2634
2635
2636 /**********************************************************************
2637 ga_resurect()
2638 synopsis: Restores a population structure into the population
2639 table from an external source.
2640 parameters: population * population pointer
2641 return: unsigned int population id (or -1)
2642 last updated: 15 Aug 2002
2643 **********************************************************************/
2644
ga_resurect(population * pop)2645 unsigned int ga_resurect(population *pop)
2646 {
2647 unsigned int id=TABLE_ERROR_INDEX; /* Internal population id. */
2648
2649 if ( !pop ) die("Null pointer to population structure passed.");
2650
2651 plog(LOG_VERBOSE, "The population has been restored!");
2652
2653 THREAD_LOCK(pop_table_lock);
2654 if (pop_table)
2655 {
2656 id = table_add(pop_table, pop);
2657 }
2658 THREAD_UNLOCK(pop_table_lock);
2659
2660 return id;
2661 }
2662
2663
2664 /**********************************************************************
2665 ga_extinction()
2666 synopsis: Purge all memory used by a population, also remove
2667 it from the population table.
2668 parameters:
2669 return:
2670 last updated: 15 Aug 2002
2671 **********************************************************************/
2672
ga_extinction(population * extinct)2673 boolean ga_extinction(population *extinct)
2674 {
2675 unsigned int id = TABLE_ERROR_INDEX; /* Internal index for this extinct population. */
2676
2677 if ( !extinct ) die("Null pointer to population structure passed.");
2678
2679 plog(LOG_VERBOSE, "This population is becoming extinct!");
2680
2681 /*
2682 * Remove this population from the population table.
2683 */
2684 THREAD_LOCK(pop_table_lock);
2685 if (pop_table)
2686 {
2687 id = table_remove_data(pop_table, extinct);
2688 if (table_count_items(pop_table) < 1)
2689 {
2690 table_destroy(pop_table);
2691 pop_table=NULL;
2692 }
2693 }
2694 THREAD_UNLOCK(pop_table_lock);
2695
2696 /*
2697 * Error check.
2698 */
2699 if (id == TABLE_ERROR_INDEX)
2700 die("Unable to find population structure in table.");
2701
2702 /*
2703 * Any user-data?
2704 */
2705 if (extinct->data)
2706 plog(LOG_WARNING, "User data field is not empty. (Potential memory leak)");
2707
2708 /*
2709 * Dereference/free everyting.
2710 */
2711 if (!ga_genocide(extinct, 0))
2712 {
2713 plog(LOG_NORMAL, "This population is already extinct!");
2714 }
2715 else
2716 {
2717 s_free(extinct->entity_array);
2718 s_free(extinct->entity_iarray);
2719 mem_chunk_destroy(extinct->entity_chunk);
2720
2721 #if USE_CHROMO_CHUNKS == 1
2722 mem_chunk_destroy(extinct->chromo_chunk);
2723 mem_chunk_destroy(extinct->chromoarray_chunk);
2724 #endif
2725
2726 if (extinct->tabu_params) s_free(extinct->tabu_params);
2727 if (extinct->sa_params) s_free(extinct->sa_params);
2728 if (extinct->dc_params) s_free(extinct->dc_params);
2729 if (extinct->climbing_params) s_free(extinct->climbing_params);
2730 if (extinct->simplex_params) s_free(extinct->simplex_params);
2731 if (extinct->gradient_params) s_free(extinct->gradient_params);
2732 if (extinct->search_params) s_free(extinct->search_params);
2733 if (extinct->sampling_params) s_free(extinct->sampling_params);
2734
2735 THREAD_LOCK_FREE(extinct->lock);
2736 #if USE_CHROMO_CHUNKS == 1
2737 THREAD_LOCK_FREE(extinct->chromo_chunk_lock);
2738 #endif
2739
2740 s_free(extinct);
2741 }
2742
2743 return TRUE;
2744 }
2745
2746
2747 /**********************************************************************
2748 ga_genocide()
2749 synopsis: Kill entities to reduce population size down to
2750 specified value.
2751 parameters:
2752 return:
2753 last updated: 22 Aug 2002
2754 **********************************************************************/
2755
ga_genocide(population * pop,int target_size)2756 boolean ga_genocide(population *pop, int target_size)
2757 {
2758 if ( !pop ) return FALSE;
2759
2760 plog(LOG_VERBOSE,
2761 "The population is being culled from %d to %d individuals!",
2762 pop->size, target_size);
2763
2764 /*
2765 * Dereference the structures relating to the least
2766 * fit population members until the desired population size in reached.
2767 */
2768 while (pop->size>target_size)
2769 {
2770 /*printf("Dereferencing entity with rank %d (fitness = %d)\n",
2771 pop->size-1, pop->entity_iarray[pop->size-1]->fitness);*/
2772 ga_entity_dereference_by_rank(pop, pop->size-1);
2773 }
2774
2775 return TRUE;
2776 }
2777
2778
2779 /**********************************************************************
2780 ga_genocide_by_fitness()
2781 synopsis: Kill entities with fitness equal to or worse than
2782 specified value.
2783 parameters:
2784 return:
2785 last updated: 01 Jul 2004
2786 **********************************************************************/
2787
ga_genocide_by_fitness(population * pop,double target_fitness)2788 boolean ga_genocide_by_fitness(population *pop, double target_fitness)
2789 {
2790 if ( !pop ) return FALSE;
2791
2792 plog(LOG_VERBOSE,
2793 "The population is being culled at fitness %f!",
2794 pop->size, target_fitness);
2795
2796 /*
2797 * Dereference the structures relating to the least
2798 * fit population members until the desired population size in reached.
2799 */
2800 while ( pop->size>0 &&
2801 pop->entity_iarray[pop->size-1]->fitness<target_fitness )
2802 {
2803 /*printf("Dereferencing entity with rank %d (fitness = %d)\n",
2804 pop->size-1, pop->entity_iarray[pop->size-1]->fitness);*/
2805 ga_entity_dereference_by_rank(pop, pop->size-1);
2806 }
2807
2808 return TRUE;
2809 }
2810
2811
2812 /**********************************************************************
2813 ga_entity_get_fitness()
2814 synopsis: Gets an entity's fitness.
2815 parameters:
2816 return:
2817 last updated: 23 May 2002
2818 **********************************************************************/
2819
ga_entity_get_fitness(entity * e)2820 double ga_entity_get_fitness(entity *e)
2821 {
2822
2823 return e?e->fitness:GA_MIN_FITNESS;
2824 }
2825
2826
2827 /**********************************************************************
2828 ga_entity_set_fitness()
2829 synopsis: Gets an entity's fitness.
2830 parameters:
2831 return:
2832 last updated: 23 May 2002
2833 **********************************************************************/
2834
ga_entity_set_fitness(entity * e,double fitness)2835 boolean ga_entity_set_fitness(entity *e, double fitness)
2836 {
2837 if ( !e ) return FALSE;
2838
2839 e->fitness=fitness;
2840
2841 return TRUE;
2842 }
2843
2844
2845 /**********************************************************************
2846 ga_population_get_stablesize()
2847 synopsis: Gets a population's stable size.
2848 parameters:
2849 return:
2850 last updated: 23 May 2002
2851 **********************************************************************/
2852
ga_population_get_stablesize(population * pop)2853 int ga_population_get_stablesize(population *pop)
2854 {
2855
2856 return pop?pop->stable_size:0;
2857 }
2858
2859
2860 /**********************************************************************
2861 ga_population_get_size()
2862 synopsis: Gets a population's current size.
2863 parameters:
2864 return:
2865 last updated: 23 May 2002
2866 **********************************************************************/
2867
ga_population_get_size(population * pop)2868 int ga_population_get_size(population *pop)
2869 {
2870
2871 return pop?pop->size:0;
2872 }
2873
2874
2875 /**********************************************************************
2876 ga_population_get_maxsize()
2877 synopsis: Gets a population's maximum size. (I don't know why
2878 anyone would need this function, but it is here for
2879 completeness.)
2880 parameters:
2881 return:
2882 last updated: 23 May 2002
2883 **********************************************************************/
2884
ga_population_get_maxsize(population * pop)2885 int ga_population_get_maxsize(population *pop)
2886 {
2887
2888 return pop?pop->max_size:0;
2889 }
2890
2891
2892 /**********************************************************************
2893 ga_population_set_stablesize()
2894 synopsis: Gets a population's stable size.
2895 parameters:
2896 return:
2897 last updated: 23 May 2002
2898 **********************************************************************/
2899
ga_population_set_stablesize(population * pop,int stable_size)2900 boolean ga_population_set_stablesize(population *pop, int stable_size)
2901 {
2902 if ( !pop ) return FALSE;
2903
2904 pop->stable_size = stable_size;
2905
2906 return TRUE;
2907 }
2908
2909
2910 /**********************************************************************
2911 ga_population_set_data()
2912 synopsis: Sets the population's user data.
2913 parameters:
2914 return:
2915 last updated: 08 Nov 2002
2916 **********************************************************************/
2917
ga_population_set_data(population * pop,vpointer data)2918 boolean ga_population_set_data(population *pop, vpointer data)
2919 {
2920 if ( !pop ) return FALSE;
2921
2922 pop->data = data;
2923
2924 return TRUE;
2925 }
2926
2927
2928 /**********************************************************************
2929 ga_population_get_data()
2930 synopsis: Gets the population's user data.
2931 parameters:
2932 return:
2933 last updated: 08 Nov 2002
2934 **********************************************************************/
2935
ga_population_get_data(population * pop)2936 vpointer ga_population_get_data(population *pop)
2937 {
2938 if ( !pop ) return NULL;
2939
2940 return pop->data;
2941 }
2942
2943
2944 /**********************************************************************
2945 ga_entity_set_data()
2946 synopsis: Sets the entity's user data.
2947 parameters:
2948 return:
2949 last updated: 08 Nov 2002
2950 **********************************************************************/
2951
ga_entity_set_data(population * pop,entity * e,SLList * data)2952 boolean ga_entity_set_data(population *pop, entity *e, SLList *data)
2953 {
2954 SLList *present; /* Current list element. */
2955
2956 if ( !pop ) return FALSE;
2957 if ( !e ) return FALSE;
2958
2959 if (e->data)
2960 {
2961 if (pop->data_destructor)
2962 {
2963 present = data;
2964 while (present!=NULL)
2965 {
2966 pop->data_destructor(slink_data(present));
2967 present = slink_next(present);
2968 }
2969 }
2970 slink_free_all(e->data);
2971 }
2972
2973 e->data = data;
2974
2975 return TRUE;
2976 }
2977
2978
2979 /**********************************************************************
2980 ga_entity_get_data()
2981 synopsis: Gets the entity's user data.
2982 parameters:
2983 return:
2984 last updated: 08 Nov 2002
2985 **********************************************************************/
2986
ga_entity_get_data(population * pop,entity * e)2987 SLList *ga_entity_get_data(population *pop, entity *e)
2988 {
2989
2990 if ( !pop ) return NULL;
2991 if ( !e ) return NULL;
2992
2993 return e->data;
2994 }
2995
2996
2997 /**********************************************************************
2998 ga_population_get_generation()
2999 synopsis: Gets the current generation number. Intended for use
3000 within fitness evaluation callbacks only.
3001 parameters:
3002 return:
3003 last updated: 18 Mar 2003
3004 **********************************************************************/
3005
ga_population_get_generation(population * pop)3006 int ga_population_get_generation(population *pop)
3007 {
3008
3009 if ( !pop ) return 0;
3010
3011 return pop->generation;
3012 }
3013
3014
3015 /**********************************************************************
3016 ga_population_get_island()
3017 synopsis: Gets the current island number. Intended for use
3018 within fitness evaluation callbacks only.
3019 parameters:
3020 return:
3021 last updated: 28 Feb 2005
3022 **********************************************************************/
3023
ga_population_get_island(population * pop)3024 int ga_population_get_island(population *pop)
3025 {
3026
3027 if ( !pop ) return 0;
3028
3029 return pop->island;
3030 }
3031
3032
3033 /**********************************************************************
3034 ga_population_get_crossover()
3035 synopsis: Gets the crossover rate of a population.
3036 parameters:
3037 return:
3038 last updated: 06 Jul 2003
3039 **********************************************************************/
3040
ga_population_get_crossover(population * pop)3041 double ga_population_get_crossover(population *pop)
3042 {
3043
3044 if ( !pop ) die("Null pointer to population structure passed.");
3045
3046 return pop->crossover_ratio;
3047 }
3048
3049
3050 /**********************************************************************
3051 ga_population_get_allele_mutation_prob()
3052 synopsis: Gets the allele mutation rate of a population.
3053 parameters:
3054 return:
3055 last updated: 16 Feb 2005
3056 **********************************************************************/
3057
ga_population_get_allele_mutation_prob(population * pop)3058 double ga_population_get_allele_mutation_prob(population *pop)
3059 {
3060
3061 if ( !pop ) die("Null pointer to population structure passed.");
3062
3063 return pop->allele_mutation_prob;
3064 }
3065
3066
3067 /**********************************************************************
3068 ga_population_get_allele_min_integer()
3069 synopsis: Gets the minimum integer allele value for a population.
3070 parameters:
3071 return:
3072 last updated: 17 Feb 2005
3073 **********************************************************************/
3074
ga_population_get_allele_min_integer(population * pop)3075 int ga_population_get_allele_min_integer(population *pop)
3076 {
3077
3078 if ( !pop ) die("Null pointer to population structure passed.");
3079
3080 return pop->allele_min_integer;
3081 }
3082
3083
3084 /**********************************************************************
3085 ga_population_get_allele_max_integer()
3086 synopsis: Gets the maximum integer allele value for a population.
3087 parameters:
3088 return:
3089 last updated: 17 Feb 2005
3090 **********************************************************************/
3091
ga_population_get_allele_max_integer(population * pop)3092 int ga_population_get_allele_max_integer(population *pop)
3093 {
3094
3095 if ( !pop ) die("Null pointer to population structure passed.");
3096
3097 return pop->allele_max_integer;
3098 }
3099
3100
3101 /**********************************************************************
3102 ga_population_get_allele_min_double()
3103 synopsis: Gets the minimum double-precision allele value for a
3104 population.
3105 parameters:
3106 return:
3107 last updated: 17 Feb 2005
3108 **********************************************************************/
3109
ga_population_get_allele_min_double(population * pop)3110 double ga_population_get_allele_min_double(population *pop)
3111 {
3112
3113 if ( !pop ) die("Null pointer to population structure passed.");
3114
3115 return pop->allele_min_double;
3116 }
3117
3118
3119 /**********************************************************************
3120 ga_population_get_allele_max_double()
3121 synopsis: Gets the maximum double-precision allele value for a
3122 population.
3123 parameters:
3124 return:
3125 last updated: 17 Feb 2005
3126 **********************************************************************/
3127
ga_population_get_allele_max_double(population * pop)3128 double ga_population_get_allele_max_double(population *pop)
3129 {
3130
3131 if ( !pop ) die("Null pointer to population structure passed.");
3132
3133 return pop->allele_max_double;
3134 }
3135
3136
3137 /**********************************************************************
3138 ga_population_get_mutation()
3139 synopsis: Gets the mutation rate of a population.
3140 parameters:
3141 return:
3142 last updated: 06 Jul 2003
3143 **********************************************************************/
3144
ga_population_get_mutation(population * pop)3145 double ga_population_get_mutation(population *pop)
3146 {
3147
3148 if ( !pop ) die("Null pointer to population structure passed.");
3149
3150 return pop->mutation_ratio;
3151 }
3152
3153
3154 /**********************************************************************
3155 ga_population_get_migration()
3156 synopsis: Gets the migration rate of a population.
3157 parameters:
3158 return:
3159 last updated: 06 Jul 2003
3160 **********************************************************************/
3161
ga_population_get_migration(population * pop)3162 double ga_population_get_migration(population *pop)
3163 {
3164
3165 if ( !pop ) die("Null pointer to population structure passed.");
3166
3167 return pop->migration_ratio;
3168 }
3169
3170
3171 /**********************************************************************
3172 ga_population_get_scheme()
3173 synopsis: Gets the evolutionary scheme of a population.
3174 parameters:
3175 return:
3176 last updated: 06 Jul 2003
3177 **********************************************************************/
3178
ga_population_get_scheme(population * pop)3179 ga_scheme_type ga_population_get_scheme(population *pop)
3180 {
3181
3182 if ( !pop ) die("Null pointer to population structure passed.");
3183
3184 return pop->scheme;
3185 }
3186
3187
3188 /**********************************************************************
3189 ga_population_get_elitism()
3190 synopsis: Gets the elitism mode of a population.
3191 parameters:
3192 return:
3193 last updated: 06 Jul 2003
3194 **********************************************************************/
3195
ga_population_get_elitism(population * pop)3196 ga_elitism_type ga_population_get_elitism(population *pop)
3197 {
3198
3199 if ( !pop ) die("Null pointer to population structure passed.");
3200
3201 return pop->elitism;
3202 }
3203
3204
3205 /**********************************************************************
3206 ga_init_openmp()
3207 synopsis: Initialises OpenMP code.
3208 This function must be called in OpenMP enabled code,
3209 but the ga_genesis_XXX() functions do this.
3210 parameters: none
3211 return: none
3212 last updated: 03 May 2004
3213 **********************************************************************/
3214
ga_init_openmp(void)3215 void ga_init_openmp( void )
3216 {
3217
3218 #if USE_OPENMP == 1
3219 #pragma omp single
3220 {
3221 if (gaul_openmp_initialised == FALSE)
3222 {
3223 avltree_init_openmp();
3224 linkedlist_init_openmp();
3225 memory_init_openmp();
3226 mem_chunk_init_openmp();
3227 random_seed(0);
3228
3229 omp_init_lock(&pop_table_lock);
3230 gaul_openmp_initialised = TRUE;
3231 }
3232 }
3233 #endif
3234
3235 return;
3236 }
3237
3238
3239