-
-
Notifications
You must be signed in to change notification settings - Fork 476
/
Copy pathpygad.py
2620 lines (2351 loc) · 198 KB
/
pygad.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy
import random
import cloudpickle
import warnings
import concurrent.futures
import inspect
import logging
from pygad import utils
from pygad import helper
from pygad import visualize
# Extend all the classes so that they can be referenced by just the `self` object of the `pygad.GA` class.
class GA(utils.parent_selection.ParentSelection,
utils.crossover.Crossover,
utils.mutation.Mutation,
utils.nsga2.NSGA2,
helper.unique.Unique,
visualize.plot.Plot):
supported_int_types = [int, numpy.int8, numpy.int16, numpy.int32, numpy.int64,
numpy.uint, numpy.uint8, numpy.uint16, numpy.uint32, numpy.uint64,
object]
supported_float_types = [float, numpy.float16, numpy.float32, numpy.float64,
object]
supported_int_float_types = supported_int_types + supported_float_types
def __init__(self,
num_generations,
num_parents_mating,
fitness_func,
fitness_batch_size=None,
initial_population=None,
sol_per_pop=None,
num_genes=None,
init_range_low=-4,
init_range_high=4,
gene_type=float,
parent_selection_type="sss",
keep_parents=-1,
keep_elitism=1,
K_tournament=3,
crossover_type="single_point",
crossover_probability=None,
mutation_type="random",
mutation_probability=None,
mutation_by_replacement=False,
mutation_percent_genes='default',
mutation_num_genes=None,
random_mutation_min_val=-1.0,
random_mutation_max_val=1.0,
gene_space=None,
allow_duplicate_genes=True,
on_start=None,
on_fitness=None,
on_parents=None,
on_crossover=None,
on_mutation=None,
on_generation=None,
on_stop=None,
save_best_solutions=False,
save_solutions=False,
suppress_warnings=False,
stop_criteria=None,
parallel_processing=None,
random_seed=None,
logger=None):
"""
The constructor of the GA class accepts all parameters required to create an instance of the GA class. It validates such parameters.
num_generations: Number of generations.
num_parents_mating: Number of solutions to be selected as parents in the mating pool.
fitness_func: Accepts a function/method and returns the fitness value of the solution. In PyGAD 2.20.0, a third parameter is passed referring to the 'pygad.GA' instance. If method, then it must accept 4 parameters where the fourth one refers to the method's object.
fitness_batch_size: Added in PyGAD 2.19.0. Supports calculating the fitness in batches. If the value is 1 or None, then the fitness function is called for each invidiaul solution. If given another value X where X is neither 1 nor None (e.g. X=3), then the fitness function is called once for each X (3) solutions.
initial_population: A user-defined initial population. It is useful when the user wants to start the generations with a custom initial population. It defaults to None which means no initial population is specified by the user. In this case, PyGAD creates an initial population using the 'sol_per_pop' and 'num_genes' parameters. An exception is raised if the 'initial_population' is None while any of the 2 parameters ('sol_per_pop' or 'num_genes') is also None.
sol_per_pop: Number of solutions in the population.
num_genes: Number of parameters in the function.
init_range_low: The lower value of the random range from which the gene values in the initial population are selected. It defaults to -4. Available in PyGAD 1.0.20 and higher.
init_range_high: The upper value of the random range from which the gene values in the initial population are selected. It defaults to -4. Available in PyGAD 1.0.20.
# It is OK to set the value of any of the 2 parameters ('init_range_low' and 'init_range_high') to be equal, higher or lower than the other parameter (i.e. init_range_low is not needed to be lower than init_range_high).
gene_type: The type of the gene. It is assigned to any of these types (int, numpy.int8, numpy.int16, numpy.int32, numpy.int64, numpy.uint, numpy.uint8, numpy.uint16, numpy.uint32, numpy.uint64, float, numpy.float16, numpy.float32, numpy.float64) and forces all the genes to be of that type.
parent_selection_type: Type of parent selection.
keep_parents: If 0, this means no parent in the current population will be used in the next population. If -1, this means all parents in the current population will be used in the next population. If set to a value > 0, then the specified value refers to the number of parents in the current population to be used in the next population. Some parent selection operators such as rank selection, favor population diversity and therefore keeping the parents in the next generation can be beneficial. However, some other parent selection operators, such as roulette wheel selection (RWS), have higher selection pressure and keeping more than one parent in the next generation can seriously harm population diversity. This parameter have an effect only when the keep_elitism parameter is 0. Thanks to Prof. Fernando Jiménez Barrionuevo (http://webs.um.es/fernan) for editing this sentence.
K_tournament: When the value of 'parent_selection_type' is 'tournament', the 'K_tournament' parameter specifies the number of solutions from which a parent is selected randomly.
keep_elitism: Added in PyGAD 2.18.0. It can take the value 0 or a positive integer that satisfies (0 <= keep_elitism <= sol_per_pop). It defaults to 1 which means only the best solution in the current generation is kept in the next generation. If assigned 0, this means it has no effect. If assigned a positive integer K, then the best K solutions are kept in the next generation. It cannot be assigned a value greater than the value assigned to the sol_per_pop parameter. If this parameter has a value different than 0, then the keep_parents parameter will have no effect.
crossover_type: Type of the crossover opreator. If crossover_type=None, then the crossover step is bypassed which means no crossover is applied and thus no offspring will be created in the next generations. The next generation will use the solutions in the current population.
crossover_probability: The probability of selecting a solution for the crossover operation. If the solution probability is <= crossover_probability, the solution is selected. The value must be between 0 and 1 inclusive.
mutation_type: Type of the mutation opreator. If mutation_type=None, then the mutation step is bypassed which means no mutation is applied and thus no changes are applied to the offspring created using the crossover operation. The offspring will be used unchanged in the next generation.
mutation_probability: The probability of selecting a gene for the mutation operation. If the gene probability is <= mutation_probability, the gene is selected. It accepts either a single value for fixed mutation or a list/tuple/numpy.ndarray of 2 values for adaptive mutation. The values must be between 0 and 1 inclusive. If specified, then no need for the 2 parameters mutation_percent_genes and mutation_num_genes.
mutation_by_replacement: An optional bool parameter. It works only when the selected type of mutation is random (mutation_type="random"). In this case, setting mutation_by_replacement=True means replace the gene by the randomly generated value. If False, then it has no effect and random mutation works by adding the random value to the gene.
mutation_percent_genes: Percentage of genes to mutate which defaults to the string 'default' which means 10%. This parameter has no action if any of the 2 parameters mutation_probability or mutation_num_genes exist.
mutation_num_genes: Number of genes to mutate which defaults to None. If the parameter mutation_num_genes exists, then no need for the parameter mutation_percent_genes. This parameter has no action if the mutation_probability parameter exists.
random_mutation_min_val: The minimum value of the range from which a random value is selected to be added to the selected gene(s) to mutate. It defaults to -1.0.
random_mutation_max_val: The maximum value of the range from which a random value is selected to be added to the selected gene(s) to mutate. It defaults to 1.0.
gene_space: It accepts a list of all possible values of the gene. This list is used in the mutation step. Should be used only if the gene space is a set of discrete values. No need for the 2 parameters (random_mutation_min_val and random_mutation_max_val) if the parameter gene_space exists. Added in PyGAD 2.5.0. In PyGAD 2.11.0, the gene_space can be assigned a dict.
on_start: Accepts a function/method to be called only once before the genetic algorithm starts its evolution. If function, then it must accept a single parameter representing the instance of the genetic algorithm. If method, then it must accept 2 parameters where the second one refers to the method's object. Added in PyGAD 2.6.0.
on_fitness: Accepts a function/method to be called after calculating the fitness values of all solutions in the population. If function, then it must accept 2 parameters: 1) a list of all solutions' fitness values 2) the instance of the genetic algorithm. If method, then it must accept 3 parameters where the third one refers to the method's object. Added in PyGAD 2.6.0.
on_parents: Accepts a function/method to be called after selecting the parents that mates. If function, then it must accept 2 parameters: the first one represents the instance of the genetic algorithm and the second one represents the selected parents. If method, then it must accept 3 parameters where the third one refers to the method's object. Added in PyGAD 2.6.0.
on_crossover: Accepts a function/method to be called each time the crossover operation is applied. If function, then it must accept 2 parameters: the first one represents the instance of the genetic algorithm and the second one represents the offspring generated using crossover. If method, then it must accept 3 parameters where the third one refers to the method's object. Added in PyGAD 2.6.0.
on_mutation: Accepts a function/method to be called each time the mutation operation is applied. If function, then it must accept 2 parameters: the first one represents the instance of the genetic algorithm and the second one represents the offspring after applying the mutation. If method, then it must accept 3 parameters where the third one refers to the method's object. Added in PyGAD 2.6.0.
on_generation: Accepts a function/method to be called after each generation. If function, then it must accept a single parameter representing the instance of the genetic algorithm. If the function returned "stop", then the run() method stops without completing the other generations. If method, then it must accept 2 parameters where the second one refers to the method's object. Added in PyGAD 2.6.0.
on_stop: Accepts a function/method to be called only once exactly before the genetic algorithm stops or when it completes all the generations. If function, then it must accept 2 parameters: the first one represents the instance of the genetic algorithm and the second one is a list of fitness values of the last population's solutions. If method, then it must accept 3 parameters where the third one refers to the method's object. Added in PyGAD 2.6.0.
save_best_solutions: Added in PyGAD 2.9.0 and its type is bool. If True, then the best solution in each generation is saved into the 'best_solutions' attribute. Use this parameter with caution as it may cause memory overflow when either the number of generations or the number of genes is large.
save_solutions: Added in PyGAD 2.15.0 and its type is bool. If True, then all solutions in each generation are saved into the 'solutions' attribute. Use this parameter with caution as it may cause memory overflow when either the number of generations, number of genes, or number of solutions in population is large.
suppress_warnings: Added in PyGAD 2.10.0 and its type is bool. If True, then no warning messages will be displayed. It defaults to False.
allow_duplicate_genes: Added in PyGAD 2.13.0. If True, then a solution/chromosome may have duplicate gene values. If False, then each gene will have a unique value in its solution.
stop_criteria: Added in PyGAD 2.15.0. It is assigned to some criteria to stop the evolution if at least one criterion holds.
parallel_processing: Added in PyGAD 2.17.0. Defaults to `None` which means no parallel processing is used. If a positive integer is assigned, it specifies the number of threads to be used. If a list or a tuple of exactly 2 elements is assigned, then: 1) The first element can be either "process" or "thread" to specify whether processes or threads are used, respectively. 2) The second element can be: 1) A positive integer to select the maximum number of processes or threads to be used. 2) 0 to indicate that parallel processing is not used. This is identical to setting 'parallel_processing=None'. 3) None to use the default value as calculated by the concurrent.futures module.
random_seed: Added in PyGAD 2.18.0. It defines the random seed to be used by the random function generators (we use random functions in the NumPy and random modules). This helps to reproduce the same results by setting the same random seed.
logger: Added in PyGAD 2.20.0. It accepts a logger object of the 'logging.Logger' class to log the messages. If no logger is passed, then a default logger is created to log/print the messages to the console exactly like using the 'print()' function.
"""
try:
# If no logger is passed, then create a logger that logs only the messages to the console.
if logger is None:
# Create a logger named with the module name.
logger = logging.getLogger(__name__)
# Set the logger log level to 'DEBUG' to log all kinds of messages.
logger.setLevel(logging.DEBUG)
# Clear any attached handlers to the logger from the previous runs.
# If the handlers are not cleared, then the new handler will be appended to the list of handlers.
# This makes the single log message be repeated according to the length of the list of handlers.
logger.handlers.clear()
# Create the handlers.
stream_handler = logging.StreamHandler()
# Set the handler log level to 'DEBUG' to log all kinds of messages received from the logger.
stream_handler.setLevel(logging.DEBUG)
# Create the formatter that just includes the log message.
formatter = logging.Formatter('%(message)s')
# Add the formatter to the handler.
stream_handler.setFormatter(formatter)
# Add the handler to the logger.
logger.addHandler(stream_handler)
else:
# Validate that the passed logger is of type 'logging.Logger'.
if isinstance(logger, logging.Logger):
pass
else:
raise TypeError(f"The expected type of the 'logger' parameter is 'logging.Logger' but {type(logger)} found.")
# Create the 'self.logger' attribute to hold the logger.
# Instead of using 'print()', use 'self.logger.info()'
self.logger = logger
self.random_seed = random_seed
if random_seed is None:
pass
else:
numpy.random.seed(self.random_seed)
random.seed(self.random_seed)
# If suppress_warnings is bool and its valud is False, then print warning messages.
if type(suppress_warnings) is bool:
self.suppress_warnings = suppress_warnings
else:
self.valid_parameters = False
raise TypeError(f"The expected type of the 'suppress_warnings' parameter is bool but {type(suppress_warnings)} found.")
# Validating mutation_by_replacement
if not (type(mutation_by_replacement) is bool):
self.valid_parameters = False
raise TypeError(f"The expected type of the 'mutation_by_replacement' parameter is bool but {type(mutation_by_replacement)} found.")
self.mutation_by_replacement = mutation_by_replacement
# Validate allow_duplicate_genes
if not (type(allow_duplicate_genes) is bool):
self.valid_parameters = False
raise TypeError(f"The expected type of the 'allow_duplicate_genes' parameter is bool but {type(allow_duplicate_genes)} found.")
self.allow_duplicate_genes = allow_duplicate_genes
# Validate gene_space
self.gene_space_nested = False
if type(gene_space) is type(None):
pass
elif type(gene_space) is range:
if len(gene_space) == 0:
self.valid_parameters = False
raise ValueError("'gene_space' cannot be empty (i.e. its length must be >= 0).")
elif type(gene_space) in [list, numpy.ndarray]:
if len(gene_space) == 0:
self.valid_parameters = False
raise ValueError("'gene_space' cannot be empty (i.e. its length must be >= 0).")
else:
for index, el in enumerate(gene_space):
if type(el) in [numpy.ndarray, list, tuple, range]:
if len(el) == 0:
self.valid_parameters = False
raise ValueError(f"The element indexed {index} of 'gene_space' with type {type(el)} cannot be empty (i.e. its length must be >= 0).")
else:
for val in el:
if not (type(val) in [type(None)] + GA.supported_int_float_types):
raise TypeError(f"All values in the sublists inside the 'gene_space' attribute must be numeric of type int/float/None but ({val}) of type {type(val)} found.")
self.gene_space_nested = True
elif type(el) == type(None):
pass
# self.gene_space_nested = True
elif type(el) is dict:
if len(el.items()) == 2:
if ('low' in el.keys()) and ('high' in el.keys()):
pass
else:
self.valid_parameters = False
raise ValueError(f"When an element in the 'gene_space' parameter is of type dict, then it can have the keys 'low', 'high', and 'step' (optional) but the following keys found: {el.keys()}")
elif len(el.items()) == 3:
if ('low' in el.keys()) and ('high' in el.keys()) and ('step' in el.keys()):
pass
else:
self.valid_parameters = False
raise ValueError(f"When an element in the 'gene_space' parameter is of type dict, then it can have the keys 'low', 'high', and 'step' (optional) but the following keys found: {el.keys()}")
else:
self.valid_parameters = False
raise ValueError(f"When an element in the 'gene_space' parameter is of type dict, then it must have only 2 items but ({len(el.items())}) items found.")
self.gene_space_nested = True
elif not (type(el) in GA.supported_int_float_types):
self.valid_parameters = False
raise TypeError(f"Unexpected type {type(el)} for the element indexed {index} of 'gene_space'. The accepted types are list/tuple/range/numpy.ndarray of numbers, a single number (int/float), or None.")
elif type(gene_space) is dict:
if len(gene_space.items()) == 2:
if ('low' in gene_space.keys()) and ('high' in gene_space.keys()):
pass
else:
self.valid_parameters = False
raise ValueError(f"When the 'gene_space' parameter is of type dict, then it can have only the keys 'low', 'high', and 'step' (optional) but the following keys found: {gene_space.keys()}")
elif len(gene_space.items()) == 3:
if ('low' in gene_space.keys()) and ('high' in gene_space.keys()) and ('step' in gene_space.keys()):
pass
else:
self.valid_parameters = False
raise ValueError(f"When the 'gene_space' parameter is of type dict, then it can have only the keys 'low', 'high', and 'step' (optional) but the following keys found: {gene_space.keys()}")
else:
self.valid_parameters = False
raise ValueError(f"When the 'gene_space' parameter is of type dict, then it must have only 2 items but ({len(gene_space.items())}) items found.")
else:
self.valid_parameters = False
raise TypeError(f"The expected type of 'gene_space' is list, range, or numpy.ndarray but {type(gene_space)} found.")
self.gene_space = gene_space
# Validate init_range_low and init_range_high
# if type(init_range_low) in GA.supported_int_float_types:
# if type(init_range_high) in GA.supported_int_float_types:
# self.init_range_low = init_range_low
# self.init_range_high = init_range_high
# else:
# self.valid_parameters = False
# raise ValueError(f"The value passed to the 'init_range_high' parameter must be either integer or floating-point number but the value ({init_range_high}) of type {type(init_range_high)} found.")
# else:
# self.valid_parameters = False
# raise ValueError(f"The value passed to the 'init_range_low' parameter must be either integer or floating-point number but the value ({init_range_low}) of type {type(init_range_low)} found.")
# Validate init_range_low and init_range_high
if type(init_range_low) in GA.supported_int_float_types:
if type(init_range_high) in GA.supported_int_float_types:
if init_range_low == init_range_high:
if not self.suppress_warnings:
warnings.warn("The values of the 2 parameters 'init_range_low' and 'init_range_high' are equal and this might return the same value for some genes in the initial population.")
else:
self.valid_parameters = False
raise TypeError(f"Type mismatch between the 2 parameters 'init_range_low' {type(init_range_low)} and 'init_range_high' {type(init_range_high)}.")
elif type(init_range_low) in [list, tuple, numpy.ndarray]:
# The self.num_genes attribute is not created yet.
# if len(init_range_low) == self.num_genes:
# pass
# else:
# self.valid_parameters = False
# raise ValueError(f"The length of the 'init_range_low' parameter is {len(init_range_low)} which is different from the number of genes {self.num_genes}.")
# Get the number of genes before validating the num_genes parameter.
if num_genes is None:
if initial_population is None:
self.valid_parameters = False
raise TypeError("When the parameter 'initial_population' is None, then the 2 parameters 'sol_per_pop' and 'num_genes' cannot be None too.")
elif not len(init_range_low) == len(initial_population[0]):
self.valid_parameters = False
raise ValueError(f"The length of the 'init_range_low' parameter is {len(init_range_low)} which is different from the number of genes {len(initial_population[0])}.")
elif not len(init_range_low) == num_genes:
self.valid_parameters = False
raise ValueError(f"The length of the 'init_range_low' parameter is {len(init_range_low)} which is different from the number of genes {num_genes}.")
if type(init_range_high) in [list, tuple, numpy.ndarray]:
if len(init_range_low) == len(init_range_high):
pass
else:
self.valid_parameters = False
raise ValueError(f"Size mismatch between the 2 parameters 'init_range_low' {len(init_range_low)} and 'init_range_high' {len(init_range_high)}.")
# Validate the values in init_range_low
for val in init_range_low:
if type(val) in GA.supported_int_float_types:
pass
else:
self.valid_parameters = False
raise TypeError(f"When an iterable (list/tuple/numpy.ndarray) is assigned to the 'init_range_low' parameter, its elements must be numeric but the value {val} of type {type(val)} found.")
# Validate the values in init_range_high
for val in init_range_high:
if type(val) in GA.supported_int_float_types:
pass
else:
self.valid_parameters = False
raise TypeError(f"When an iterable (list/tuple/numpy.ndarray) is assigned to the 'init_range_high' parameter, its elements must be numeric but the value {val} of type {type(val)} found.")
else:
self.valid_parameters = False
raise TypeError(f"Type mismatch between the 2 parameters 'init_range_low' {type(init_range_low)} and 'init_range_high' {type(init_range_high)}. Both of them can be either numeric or iterable (list/tuple/numpy.ndarray).")
else:
self.valid_parameters = False
raise TypeError(f"The expected type of the 'init_range_low' parameter is numeric or list/tuple/numpy.ndarray but {type(init_range_low)} found.")
self.init_range_low = init_range_low
self.init_range_high = init_range_high
# Validate gene_type
if gene_type in GA.supported_int_float_types:
self.gene_type = [gene_type, None]
self.gene_type_single = True
# A single data type of float with precision.
elif len(gene_type) == 2 and gene_type[0] in GA.supported_float_types and (type(gene_type[1]) in GA.supported_int_types or gene_type[1] is None):
self.gene_type = gene_type
self.gene_type_single = True
# A single data type of integer with precision None ([int, None]).
elif len(gene_type) == 2 and gene_type[0] in GA.supported_int_types and gene_type[1] is None:
self.gene_type = gene_type
self.gene_type_single = True
# Raise an exception for a single data type of int with integer precision.
elif len(gene_type) == 2 and gene_type[0] in GA.supported_int_types and (type(gene_type[1]) in GA.supported_int_types or gene_type[1] is None):
self.gene_type_single = False
raise ValueError(f"Integers cannot have precision. Please use the integer data type directly instead of {gene_type}.")
elif type(gene_type) in [list, tuple, numpy.ndarray]:
# Get the number of genes before validating the num_genes parameter.
if num_genes is None:
if initial_population is None:
self.valid_parameters = False
raise TypeError("When the parameter 'initial_population' is None, then the 2 parameters 'sol_per_pop' and 'num_genes' cannot be None too.")
elif not len(gene_type) == len(initial_population[0]):
self.valid_parameters = False
raise ValueError(f"When the parameter 'gene_type' is nested, then it can be either [float, int<precision>] or with length equal to the number of genes parameter. Instead, value {gene_type} with len(gene_type) ({len(gene_type)}) != number of genes ({len(initial_population[0])}) found.")
elif not len(gene_type) == num_genes:
self.valid_parameters = False
raise ValueError(f"When the parameter 'gene_type' is nested, then it can be either [float, int<precision>] or with length equal to the value passed to the 'num_genes' parameter. Instead, value {gene_type} with len(gene_type) ({len(gene_type)}) != len(num_genes) ({num_genes}) found.")
for gene_type_idx, gene_type_val in enumerate(gene_type):
if gene_type_val in GA.supported_int_float_types:
# If the gene type is float and no precision is passed or an integer, set its precision to None.
gene_type[gene_type_idx] = [gene_type_val, None]
elif type(gene_type_val) in [list, tuple, numpy.ndarray]:
# A float type is expected in a list/tuple/numpy.ndarray of length 2.
if len(gene_type_val) == 2:
if gene_type_val[0] in GA.supported_float_types:
if type(gene_type_val[1]) in GA.supported_int_types:
pass
else:
self.valid_parameters = False
raise TypeError(f"In the 'gene_type' parameter, the precision for float gene data types must be an integer but the element {gene_type_val} at index {gene_type_idx} has a precision of {gene_type_val[1]} with type {gene_type_val[0]}.")
elif gene_type_val[0] in GA.supported_int_types:
if gene_type_val[1] is None:
pass
else:
self.valid_parameters = False
raise TypeError(f"In the 'gene_type' parameter, either do not set a precision for integer data types or set it to None. But the element {gene_type_val} at index {gene_type_idx} has a precision of {gene_type_val[1]} with type {gene_type_val[0]}.")
else:
self.valid_parameters = False
raise TypeError(
f"In the 'gene_type' parameter, a precision is expected only for float gene data types but the element {gene_type_val} found at index {gene_type_idx}.\nNote that the data type must be at index 0 of the item followed by precision at index 1.")
else:
self.valid_parameters = False
raise ValueError(f"In the 'gene_type' parameter, a precision is specified in a list/tuple/numpy.ndarray of length 2 but value ({gene_type_val}) of type {type(gene_type_val)} with length {len(gene_type_val)} found at index {gene_type_idx}.")
else:
self.valid_parameters = False
raise ValueError(f"When a list/tuple/numpy.ndarray is assigned to the 'gene_type' parameter, then its elements must be of integer, floating-point, list, tuple, or numpy.ndarray data types but the value ({gene_type_val}) of type {type(gene_type_val)} found at index {gene_type_idx}.")
self.gene_type = gene_type
self.gene_type_single = False
else:
self.valid_parameters = False
raise ValueError(f"The value passed to the 'gene_type' parameter must be either a single integer, floating-point, list, tuple, or numpy.ndarray but ({gene_type}) of type {type(gene_type)} found.")
# Call the unpack_gene_space() method in the pygad.helper.unique.Unique class.
self.gene_space_unpacked = self.unpack_gene_space(range_min=self.init_range_low,
range_max=self.init_range_high)
# Build the initial population
if initial_population is None:
if (sol_per_pop is None) or (num_genes is None):
self.valid_parameters = False
raise TypeError("Error creating the initial population:\n\nWhen the parameter 'initial_population' is None, then the 2 parameters 'sol_per_pop' and 'num_genes' cannot be None too.\nThere are 2 options to prepare the initial population:\n1) Assinging the initial population to the 'initial_population' parameter. In this case, the values of the 2 parameters sol_per_pop and num_genes will be deduced.\n2) Assign integer values to the 'sol_per_pop' and 'num_genes' parameters so that PyGAD can create the initial population automatically.")
elif (type(sol_per_pop) is int) and (type(num_genes) is int):
# Validating the number of solutions in the population (sol_per_pop)
if sol_per_pop <= 0:
self.valid_parameters = False
raise ValueError(f"The number of solutions in the population (sol_per_pop) must be > 0 but ({sol_per_pop}) found. \nThe following parameters must be > 0: \n1) Population size (i.e. number of solutions per population) (sol_per_pop).\n2) Number of selected parents in the mating pool (num_parents_mating).\n")
# Validating the number of gene.
if (num_genes <= 0):
self.valid_parameters = False
raise ValueError(f"The number of genes cannot be <= 0 but ({num_genes}) found.\n")
# When initial_population=None and the 2 parameters sol_per_pop and num_genes have valid integer values, then the initial population is created.
# Inside the initialize_population() method, the initial_population attribute is assigned to keep the initial population accessible.
self.num_genes = num_genes # Number of genes in the solution.
# In case the 'gene_space' parameter is nested, then make sure the number of its elements equals to the number of genes.
if self.gene_space_nested:
if len(gene_space) != self.num_genes:
self.valid_parameters = False
raise ValueError(f"When the parameter 'gene_space' is nested, then its length must be equal to the value passed to the 'num_genes' parameter. Instead, length of gene_space ({len(gene_space)}) != num_genes ({self.num_genes})")
# Number of solutions in the population.
self.sol_per_pop = sol_per_pop
self.initialize_population(low=self.init_range_low,
high=self.init_range_high,
allow_duplicate_genes=allow_duplicate_genes,
mutation_by_replacement=True,
gene_type=self.gene_type)
else:
self.valid_parameters = False
raise TypeError(f"The expected type of both the sol_per_pop and num_genes parameters is int but {type(sol_per_pop)} and {type(num_genes)} found.")
elif not type(initial_population) in [list, tuple, numpy.ndarray]:
self.valid_parameters = False
raise TypeError(f"The value assigned to the 'initial_population' parameter is expected to by of type list, tuple, or ndarray but {type(initial_population)} found.")
elif numpy.array(initial_population).ndim != 2:
self.valid_parameters = False
raise ValueError(f"A 2D list is expected to the initial_population parameter but a ({numpy.array(initial_population).ndim}-D) list found.")
else:
# Validate the type of each value in the 'initial_population' parameter.
for row_idx in range(len(initial_population)):
for col_idx in range(len(initial_population[0])):
if type(initial_population[row_idx][col_idx]) in GA.supported_int_float_types:
pass
else:
self.valid_parameters = False
raise TypeError(f"The values in the initial population can be integers or floats but the value ({initial_population[row_idx][col_idx]}) of type {type(initial_population[row_idx][col_idx])} found.")
# Forcing the initial_population array to have the data type assigned to the gene_type parameter.
if self.gene_type_single == True:
if self.gene_type[1] == None:
self.initial_population = numpy.array(initial_population,
dtype=self.gene_type[0])
else:
# This block is reached only for non-integer data types (i.e. float).
self.initial_population = numpy.round(numpy.array(initial_population,
dtype=self.gene_type[0]),
self.gene_type[1])
else:
initial_population = numpy.array(initial_population)
self.initial_population = numpy.zeros(shape=(initial_population.shape[0],
initial_population.shape[1]),
dtype=object)
for gene_idx in range(initial_population.shape[1]):
if self.gene_type[gene_idx][1] is None:
self.initial_population[:, gene_idx] = numpy.asarray(initial_population[:, gene_idx],
dtype=self.gene_type[gene_idx][0])
else:
# This block is reached only for non-integer data types (i.e. float).
self.initial_population[:, gene_idx] = numpy.round(numpy.asarray(initial_population[:, gene_idx],
dtype=self.gene_type[gene_idx][0]),
self.gene_type[gene_idx][1])
# Check if duplicates are allowed. If not, then solve any exisiting duplicates in the passed initial population.
if self.allow_duplicate_genes == False:
for initial_solution_idx, initial_solution in enumerate(self.initial_population):
if self.gene_space is None:
self.initial_population[initial_solution_idx], _, _ = self.solve_duplicate_genes_randomly(solution=initial_solution,
min_val=self.init_range_low,
max_val=self.init_range_high,
mutation_by_replacement=self.mutation_by_replacement,
gene_type=self.gene_type,
num_trials=10)
else:
self.initial_population[initial_solution_idx], _, _ = self.solve_duplicate_genes_by_space(solution=initial_solution,
gene_type=self.gene_type,
num_trials=10)
# A NumPy array holding the initial population.
self.population = self.initial_population.copy()
# Number of genes in the solution.
self.num_genes = self.initial_population.shape[1]
# Number of solutions in the population.
self.sol_per_pop = self.initial_population.shape[0]
# The population size.
self.pop_size = (self.sol_per_pop, self.num_genes)
# Round initial_population and population
self.initial_population = self.round_genes(self.initial_population)
self.population = self.round_genes(self.population)
# In case the 'gene_space' parameter is nested, then make sure the number of its elements equals to the number of genes.
if self.gene_space_nested:
if len(gene_space) != self.num_genes:
self.valid_parameters = False
raise ValueError(f"When the parameter 'gene_space' is nested, then its length must be equal to the value passed to the 'num_genes' parameter. Instead, length of gene_space ({len(gene_space)}) != num_genes ({self.num_genes})")
# Validate random_mutation_min_val and random_mutation_max_val
if type(random_mutation_min_val) in GA.supported_int_float_types:
if type(random_mutation_max_val) in GA.supported_int_float_types:
if random_mutation_min_val == random_mutation_max_val:
if not self.suppress_warnings:
warnings.warn("The values of the 2 parameters 'random_mutation_min_val' and 'random_mutation_max_val' are equal and this might cause a fixed mutation to some genes.")
else:
self.valid_parameters = False
raise TypeError(f"Type mismatch between the 2 parameters 'random_mutation_min_val' {type(random_mutation_min_val)} and 'random_mutation_max_val' {type(random_mutation_max_val)}.")
elif type(random_mutation_min_val) in [list, tuple, numpy.ndarray]:
if len(random_mutation_min_val) == self.num_genes:
pass
else:
self.valid_parameters = False
raise ValueError(f"The length of the 'random_mutation_min_val' parameter is {len(random_mutation_min_val)} which is different from the number of genes {self.num_genes}.")
if type(random_mutation_max_val) in [list, tuple, numpy.ndarray]:
if len(random_mutation_min_val) == len(random_mutation_max_val):
pass
else:
self.valid_parameters = False
raise ValueError(f"Size mismatch between the 2 parameters 'random_mutation_min_val' {len(random_mutation_min_val)} and 'random_mutation_max_val' {len(random_mutation_max_val)}.")
# Validate the values in random_mutation_min_val
for val in random_mutation_min_val:
if type(val) in GA.supported_int_float_types:
pass
else:
self.valid_parameters = False
raise TypeError(f"When an iterable (list/tuple/numpy.ndarray) is assigned to the 'random_mutation_min_val' parameter, its elements must be numeric but the value {val} of type {type(val)} found.")
# Validate the values in random_mutation_max_val
for val in random_mutation_max_val:
if type(val) in GA.supported_int_float_types:
pass
else:
self.valid_parameters = False
raise TypeError(f"When an iterable (list/tuple/numpy.ndarray) is assigned to the 'random_mutation_max_val' parameter, its elements must be numeric but the value {val} of type {type(val)} found.")
else:
self.valid_parameters = False
raise TypeError(f"Type mismatch between the 2 parameters 'random_mutation_min_val' {type(random_mutation_min_val)} and 'random_mutation_max_val' {type(random_mutation_max_val)}.")
else:
self.valid_parameters = False
raise TypeError(f"The expected type of the 'random_mutation_min_val' parameter is numeric or list/tuple/numpy.ndarray but {type(random_mutation_min_val)} found.")
self.random_mutation_min_val = random_mutation_min_val
self.random_mutation_max_val = random_mutation_max_val
# Validating the number of parents to be selected for mating (num_parents_mating)
if num_parents_mating <= 0:
self.valid_parameters = False
raise ValueError(f"The number of parents mating (num_parents_mating) parameter must be > 0 but ({num_parents_mating}) found. \nThe following parameters must be > 0: \n1) Population size (i.e. number of solutions per population) (sol_per_pop).\n2) Number of selected parents in the mating pool (num_parents_mating).\n")
# Validating the number of parents to be selected for mating: num_parents_mating
if (num_parents_mating > self.sol_per_pop):
self.valid_parameters = False
raise ValueError(f"The number of parents to select for mating ({num_parents_mating}) cannot be greater than the number of solutions in the population ({self.sol_per_pop}) (i.e., num_parents_mating must always be <= sol_per_pop).\n")
self.num_parents_mating = num_parents_mating
# crossover: Refers to the method that applies the crossover operator based on the selected type of crossover in the crossover_type property.
# Validating the crossover type: crossover_type
if (crossover_type is None):
self.crossover = None
elif inspect.ismethod(crossover_type):
# Check if the crossover_type is a method that accepts 4 paramaters.
if (crossover_type.__code__.co_argcount == 4):
# The crossover method assigned to the crossover_type parameter is validated.
self.crossover = crossover_type
else:
self.valid_parameters = False
raise ValueError(f"When 'crossover_type' is assigned to a method, then this crossover method must accept 4 parameters:\n1) Expected to be the 'self' object.\n2) The selected parents.\n3) The size of the offspring to be produced.\n4) The instance from the pygad.GA class.\n\nThe passed crossover method named '{crossover_type.__code__.co_name}' accepts {crossover_type.__code__.co_argcount} parameter(s).")
elif callable(crossover_type):
# Check if the crossover_type is a function that accepts 2 paramaters.
if (crossover_type.__code__.co_argcount == 3):
# The crossover function assigned to the crossover_type parameter is validated.
self.crossover = crossover_type
else:
self.valid_parameters = False
raise ValueError(f"When 'crossover_type' is assigned to a function, then this crossover function must accept 3 parameters:\n1) The selected parents.\n2) The size of the offspring to be produced.3) The instance from the pygad.GA class to retrieve any property like population, gene data type, gene space, etc.\n\nThe passed crossover function named '{crossover_type.__code__.co_name}' accepts {crossover_type.__code__.co_argcount} parameter(s).")
elif not (type(crossover_type) is str):
self.valid_parameters = False
raise TypeError(f"The expected type of the 'crossover_type' parameter is either callable or str but {type(crossover_type)} found.")
else: # type crossover_type is str
crossover_type = crossover_type.lower()
if (crossover_type == "single_point"):
self.crossover = self.single_point_crossover
elif (crossover_type == "two_points"):
self.crossover = self.two_points_crossover
elif (crossover_type == "uniform"):
self.crossover = self.uniform_crossover
elif (crossover_type == "scattered"):
self.crossover = self.scattered_crossover
else:
self.valid_parameters = False
raise TypeError(f"Undefined crossover type. \nThe assigned value to the crossover_type ({crossover_type}) parameter does not refer to one of the supported crossover types which are: \n-single_point (for single point crossover)\n-two_points (for two points crossover)\n-uniform (for uniform crossover)\n-scattered (for scattered crossover).\n")
self.crossover_type = crossover_type
# Calculate the value of crossover_probability
if crossover_probability is None:
self.crossover_probability = None
elif type(crossover_probability) in GA.supported_int_float_types:
if crossover_probability >= 0 and crossover_probability <= 1:
self.crossover_probability = crossover_probability
else:
self.valid_parameters = False
raise ValueError(f"The value assigned to the 'crossover_probability' parameter must be between 0 and 1 inclusive but ({crossover_probability}) found.")
else:
self.valid_parameters = False
raise TypeError(f"Unexpected type for the 'crossover_probability' parameter. Float is expected but ({crossover_probability}) of type {type(crossover_probability)} found.")
# mutation: Refers to the method that applies the mutation operator based on the selected type of mutation in the mutation_type property.
# Validating the mutation type: mutation_type
# "adaptive" mutation is supported starting from PyGAD 2.10.0
if mutation_type is None:
self.mutation = None
elif inspect.ismethod(mutation_type):
# Check if the mutation_type is a method that accepts 3 paramater.
if (mutation_type.__code__.co_argcount == 3):
# The mutation method assigned to the mutation_type parameter is validated.
self.mutation = mutation_type
else:
self.valid_parameters = False
raise ValueError(f"When 'mutation_type' is assigned to a method, then it must accept 3 parameters:\n1) Expected to be the 'self' object.\n2) The offspring to be mutated.\n3) The instance from the pygad.GA class.\n\nThe passed mutation method named '{mutation_type.__code__.co_name}' accepts {mutation_type.__code__.co_argcount} parameter(s).")
elif callable(mutation_type):
# Check if the mutation_type is a function that accepts 2 paramater.
if (mutation_type.__code__.co_argcount == 2):
# The mutation function assigned to the mutation_type parameter is validated.
self.mutation = mutation_type
else:
self.valid_parameters = False
raise ValueError(f"When 'mutation_type' is assigned to a function, then this mutation function must accept 2 parameters:\n1) The offspring to be mutated.\n2) The instance from the pygad.GA class to retrieve any property like population, gene data type, gene space, etc.\n\nThe passed mutation function named '{mutation_type.__code__.co_name}' accepts {mutation_type.__code__.co_argcount} parameter(s).")
elif not (type(mutation_type) is str):
self.valid_parameters = False
raise TypeError(f"The expected type of the 'mutation_type' parameter is either callable or str but {type(mutation_type)} found.")
else: # type mutation_type is str
mutation_type = mutation_type.lower()
if (mutation_type == "random"):
self.mutation = self.random_mutation
elif (mutation_type == "swap"):
self.mutation = self.swap_mutation
elif (mutation_type == "scramble"):
self.mutation = self.scramble_mutation
elif (mutation_type == "inversion"):
self.mutation = self.inversion_mutation
elif (mutation_type == "adaptive"):
self.mutation = self.adaptive_mutation
else:
self.valid_parameters = False
raise TypeError(f"Undefined mutation type. \nThe assigned string value to the 'mutation_type' parameter ({mutation_type}) does not refer to one of the supported mutation types which are: \n-random (for random mutation)\n-swap (for swap mutation)\n-inversion (for inversion mutation)\n-scramble (for scramble mutation)\n-adaptive (for adaptive mutation).\n")
self.mutation_type = mutation_type
# Calculate the value of mutation_probability
if not (self.mutation_type is None):
if mutation_probability is None:
self.mutation_probability = None
elif (mutation_type != "adaptive"):
# Mutation probability is fixed not adaptive.
if type(mutation_probability) in GA.supported_int_float_types:
if mutation_probability >= 0 and mutation_probability <= 1:
self.mutation_probability = mutation_probability
else:
self.valid_parameters = False
raise ValueError(f"The value assigned to the 'mutation_probability' parameter must be between 0 and 1 inclusive but ({mutation_probability}) found.")
else:
self.valid_parameters = False
raise TypeError(f"Unexpected type for the 'mutation_probability' parameter. A numeric value is expected but ({mutation_probability}) of type {type(mutation_probability)} found.")
else:
# Mutation probability is adaptive not fixed.
if type(mutation_probability) in [list, tuple, numpy.ndarray]:
if len(mutation_probability) == 2:
for el in mutation_probability:
if type(el) in GA.supported_int_float_types:
if el >= 0 and el <= 1:
pass
else:
self.valid_parameters = False
raise ValueError(f"The values assigned to the 'mutation_probability' parameter must be between 0 and 1 inclusive but ({el}) found.")
else:
self.valid_parameters = False
raise TypeError(f"Unexpected type for a value assigned to the 'mutation_probability' parameter. A numeric value is expected but ({el}) of type {type(el)} found.")
if mutation_probability[0] < mutation_probability[1]:
if not self.suppress_warnings:
warnings.warn(f"The first element in the 'mutation_probability' parameter is {mutation_probability[0]} which is smaller than the second element {mutation_probability[1]}. This means the mutation rate for the high-quality solutions is higher than the mutation rate of the low-quality ones. This causes high disruption in the high qualitiy solutions while making little changes in the low quality solutions. Please make the first element higher than the second element.")
self.mutation_probability = mutation_probability
else:
self.valid_parameters = False
raise ValueError(f"When mutation_type='adaptive', then the 'mutation_probability' parameter must have only 2 elements but ({len(mutation_probability)}) element(s) found.")
else:
self.valid_parameters = False
raise TypeError(f"Unexpected type for the 'mutation_probability' parameter. When mutation_type='adaptive', then list/tuple/numpy.ndarray is expected but ({mutation_probability}) of type {type(mutation_probability)} found.")
else:
pass
# Calculate the value of mutation_num_genes
if not (self.mutation_type is None):
if mutation_num_genes is None:
# The mutation_num_genes parameter does not exist. Checking whether adaptive mutation is used.
if (mutation_type != "adaptive"):
# The percent of genes to mutate is fixed not adaptive.
if mutation_percent_genes == 'default'.lower():
mutation_percent_genes = 10
# Based on the mutation percentage in the 'mutation_percent_genes' parameter, the number of genes to mutate is calculated.
mutation_num_genes = numpy.uint32(
(mutation_percent_genes*self.num_genes)/100)
# Based on the mutation percentage of genes, if the number of selected genes for mutation is less than the least possible value which is 1, then the number will be set to 1.
if mutation_num_genes == 0:
if self.mutation_probability is None:
if not self.suppress_warnings:
warnings.warn(
f"The percentage of genes to mutate (mutation_percent_genes={mutation_percent_genes}) resulted in selecting ({mutation_num_genes}) genes. The number of genes to mutate is set to 1 (mutation_num_genes=1).\nIf you do not want to mutate any gene, please set mutation_type=None.")
mutation_num_genes = 1
elif type(mutation_percent_genes) in GA.supported_int_float_types:
if (mutation_percent_genes <= 0 or mutation_percent_genes > 100):
self.valid_parameters = False
raise ValueError(f"The percentage of selected genes for mutation (mutation_percent_genes) must be > 0 and <= 100 but ({mutation_percent_genes}) found.\n")
else:
# If mutation_percent_genes equals the string "default", then it is replaced by the numeric value 10.
if mutation_percent_genes == 'default'.lower():
mutation_percent_genes = 10
# Based on the mutation percentage in the 'mutation_percent_genes' parameter, the number of genes to mutate is calculated.
mutation_num_genes = numpy.uint32(
(mutation_percent_genes*self.num_genes)/100)
# Based on the mutation percentage of genes, if the number of selected genes for mutation is less than the least possible value which is 1, then the number will be set to 1.
if mutation_num_genes == 0:
if self.mutation_probability is None:
if not self.suppress_warnings:
warnings.warn(f"The percentage of genes to mutate (mutation_percent_genes={mutation_percent_genes}) resulted in selecting ({mutation_num_genes}) genes. The number of genes to mutate is set to 1 (mutation_num_genes=1).\nIf you do not want to mutate any gene, please set mutation_type=None.")
mutation_num_genes = 1
else:
self.valid_parameters = False
raise TypeError(f"Unexpected value or type of the 'mutation_percent_genes' parameter. It only accepts the string 'default' or a numeric value but ({mutation_percent_genes}) of type {type(mutation_percent_genes)} found.")
else:
# The percent of genes to mutate is adaptive not fixed.
if type(mutation_percent_genes) in [list, tuple, numpy.ndarray]:
if len(mutation_percent_genes) == 2:
mutation_num_genes = numpy.zeros_like(
mutation_percent_genes, dtype=numpy.uint32)
for idx, el in enumerate(mutation_percent_genes):
if type(el) in GA.supported_int_float_types:
if (el <= 0 or el > 100):
self.valid_parameters = False
raise ValueError(f"The values assigned to the 'mutation_percent_genes' must be > 0 and <= 100 but ({mutation_percent_genes}) found.\n")
else:
self.valid_parameters = False
raise TypeError(f"Unexpected type for a value assigned to the 'mutation_percent_genes' parameter. An integer value is expected but ({el}) of type {type(el)} found.")
# At this point of the loop, the current value assigned to the parameter 'mutation_percent_genes' is validated.
# Based on the mutation percentage in the 'mutation_percent_genes' parameter, the number of genes to mutate is calculated.
mutation_num_genes[idx] = numpy.uint32(
(mutation_percent_genes[idx]*self.num_genes)/100)
# Based on the mutation percentage of genes, if the number of selected genes for mutation is less than the least possible value which is 1, then the number will be set to 1.
if mutation_num_genes[idx] == 0:
if not self.suppress_warnings:
warnings.warn(f"The percentage of genes to mutate ({mutation_percent_genes[idx]}) resulted in selecting ({mutation_num_genes[idx]}) genes. The number of genes to mutate is set to 1 (mutation_num_genes=1).\nIf you do not want to mutate any gene, please set mutation_type=None.")
mutation_num_genes[idx] = 1
if mutation_percent_genes[0] < mutation_percent_genes[1]:
if not self.suppress_warnings:
warnings.warn(f"The first element in the 'mutation_percent_genes' parameter is ({mutation_percent_genes[0]}) which is smaller than the second element ({mutation_percent_genes[1]}).\nThis means the mutation rate for the high-quality solutions is higher than the mutation rate of the low-quality ones. This causes high disruption in the high qualitiy solutions while making little changes in the low quality solutions.\nPlease make the first element higher than the second element.")
# At this point outside the loop, all values of the parameter 'mutation_percent_genes' are validated. Eveyrthing is OK.
else:
self.valid_parameters = False
raise ValueError(f"When mutation_type='adaptive', then the 'mutation_percent_genes' parameter must have only 2 elements but ({len(mutation_percent_genes)}) element(s) found.")
else:
if self.mutation_probability is None:
self.valid_parameters = False
raise TypeError(f"Unexpected type of the 'mutation_percent_genes' parameter. When mutation_type='adaptive', then the 'mutation_percent_genes' parameter should exist and assigned a list/tuple/numpy.ndarray with 2 values but ({mutation_percent_genes}) found.")
# The mutation_num_genes parameter exists. Checking whether adaptive mutation is used.
elif (mutation_type != "adaptive"):
# Number of genes to mutate is fixed not adaptive.
if type(mutation_num_genes) in GA.supported_int_types:
if (mutation_num_genes <= 0):
self.valid_parameters = False
raise ValueError(f"The number of selected genes for mutation (mutation_num_genes) cannot be <= 0 but ({mutation_num_genes}) found. If you do not want to use mutation, please set mutation_type=None\n")
elif (mutation_num_genes > self.num_genes):
self.valid_parameters = False
raise ValueError(f"The number of selected genes for mutation (mutation_num_genes), which is ({mutation_num_genes}), cannot be greater than the number of genes ({self.num_genes}).\n")
else:
self.valid_parameters = False
raise TypeError(f"The 'mutation_num_genes' parameter is expected to be a positive integer but the value ({mutation_num_genes}) of type {type(mutation_num_genes)} found.\n")
else:
# Number of genes to mutate is adaptive not fixed.
if type(mutation_num_genes) in [list, tuple, numpy.ndarray]:
if len(mutation_num_genes) == 2:
for el in mutation_num_genes:
if type(el) in GA.supported_int_types:
if (el <= 0):
self.valid_parameters = False
raise ValueError(f"The values assigned to the 'mutation_num_genes' cannot be <= 0 but ({el}) found. If you do not want to use mutation, please set mutation_type=None\n")
elif (el > self.num_genes):
self.valid_parameters = False
raise ValueError(f"The values assigned to the 'mutation_num_genes' cannot be greater than the number of genes ({self.num_genes}) but ({el}) found.\n")
else:
self.valid_parameters = False
raise TypeError(f"Unexpected type for a value assigned to the 'mutation_num_genes' parameter. An integer value is expected but ({el}) of type {type(el)} found.")
# At this point of the loop, the current value assigned to the parameter 'mutation_num_genes' is validated.
if mutation_num_genes[0] < mutation_num_genes[1]:
if not self.suppress_warnings:
warnings.warn(f"The first element in the 'mutation_num_genes' parameter is {mutation_num_genes[0]} which is smaller than the second element {mutation_num_genes[1]}. This means the mutation rate for the high-quality solutions is higher than the mutation rate of the low-quality ones. This causes high disruption in the high qualitiy solutions while making little changes in the low quality solutions. Please make the first element higher than the second element.")
# At this point outside the loop, all values of the parameter 'mutation_num_genes' are validated. Eveyrthing is OK.
else:
self.valid_parameters = False
raise ValueError(f"When mutation_type='adaptive', then the 'mutation_num_genes' parameter must have only 2 elements but ({len(mutation_num_genes)}) element(s) found.")
else:
self.valid_parameters = False
raise TypeError(f"Unexpected type for the 'mutation_num_genes' parameter. When mutation_type='adaptive', then list/tuple/numpy.ndarray is expected but ({mutation_num_genes}) of type {type(mutation_num_genes)} found.")
else:
pass
# Validating mutation_by_replacement and mutation_type
if self.mutation_type != "random" and self.mutation_by_replacement:
if not self.suppress_warnings:
warnings.warn(f"The mutation_by_replacement parameter is set to True while the mutation_type parameter is not set to random but ({mutation_type}). Note that the mutation_by_replacement parameter has an effect only when mutation_type='random'.")
# Check if crossover and mutation are both disabled.
if (self.mutation_type is None) and (self.crossover_type is None):
if not self.suppress_warnings:
warnings.warn("The 2 parameters mutation_type and crossover_type are None. This disables any type of evolution the genetic algorithm can make. As a result, the genetic algorithm cannot find a better solution that the best solution in the initial population.")
# select_parents: Refers to a method that selects the parents based on the parent selection type specified in the parent_selection_type attribute.
# Validating the selected type of parent selection: parent_selection_type
if inspect.ismethod(parent_selection_type):
# Check if the parent_selection_type is a method that accepts 4 paramaters.
if (parent_selection_type.__code__.co_argcount == 4):
# population: Added in PyGAD 2.16.0. It should used only to support custom parent selection functions. Otherwise, it should be left to None to retirve the population by self.population.
# The parent selection method assigned to the parent_selection_type parameter is validated.
self.select_parents = parent_selection_type
else:
self.valid_parameters = False
raise ValueError(f"When 'parent_selection_type' is assigned to a method, then it must accept 4 parameters:\n1) Expected to be the 'self' object.\n2) The fitness values of the current population.\n3) The number of parents needed.\n4) The instance from the pygad.GA class.\n\nThe passed parent selection method named '{parent_selection_type.__code__.co_name}' accepts {parent_selection_type.__code__.co_argcount} parameter(s).")
elif callable(parent_selection_type):
# Check if the parent_selection_type is a function that accepts 3 paramaters.
if (parent_selection_type.__code__.co_argcount == 3):
# population: Added in PyGAD 2.16.0. It should used only to support custom parent selection functions. Otherwise, it should be left to None to retirve the population by self.population.
# The parent selection function assigned to the parent_selection_type parameter is validated.
self.select_parents = parent_selection_type
else:
self.valid_parameters = False
raise ValueError(f"When 'parent_selection_type' is assigned to a user-defined function, then this parent selection function must accept 3 parameters:\n1) The fitness values of the current population.\n2) The number of parents needed.\n3) The instance from the pygad.GA class to retrieve any property like population, gene data type, gene space, etc.\n\nThe passed parent selection function named '{parent_selection_type.__code__.co_name}' accepts {parent_selection_type.__code__.co_argcount} parameter(s).")
elif not (type(parent_selection_type) is str):
self.valid_parameters = False
raise TypeError(f"The expected type of the 'parent_selection_type' parameter is either callable or str but {type(parent_selection_type)} found.")
else:
parent_selection_type = parent_selection_type.lower()
if (parent_selection_type == "sss"):
self.select_parents = self.steady_state_selection
elif (parent_selection_type == "rws"):
self.select_parents = self.roulette_wheel_selection
elif (parent_selection_type == "sus"):
self.select_parents = self.stochastic_universal_selection
elif (parent_selection_type == "random"):
self.select_parents = self.random_selection
elif (parent_selection_type == "tournament"):
self.select_parents = self.tournament_selection
elif (parent_selection_type == "tournament_nsga2"): # Supported in PyGAD >= 3.2
self.select_parents = self.tournament_selection_nsga2
elif (parent_selection_type == "nsga2"): # Supported in PyGAD >= 3.2
self.select_parents = self.nsga2_selection
elif (parent_selection_type == "rank"):
self.select_parents = self.rank_selection
else:
self.valid_parameters = False
raise TypeError(f"Undefined parent selection type: {parent_selection_type}. \nThe assigned value to the 'parent_selection_type' parameter does not refer to one of the supported parent selection techniques which are: \n-sss (steady state selection)\n-rws (roulette wheel selection)\n-sus (stochastic universal selection)\n-rank (rank selection)\n-random (random selection)\n-tournament (tournament selection)\n-tournament_nsga2: (Tournament selection for NSGA-II)\n-nsga2: (NSGA-II parent selection).\n")
# For tournament selection, validate the K value.
if (parent_selection_type == "tournament"):
if (K_tournament > self.sol_per_pop):
K_tournament = self.sol_per_pop
if not self.suppress_warnings:
warnings.warn(f"K of the tournament selection ({K_tournament}) should not be greater than the number of solutions within the population ({self.sol_per_pop}).\nK will be clipped to be equal to the number of solutions in the population (sol_per_pop).\n")
elif (K_tournament <= 0):
self.valid_parameters = False
raise ValueError(f"K of the tournament selection cannot be <=0 but ({K_tournament}) found.\n")
self.K_tournament = K_tournament
# Validating the number of parents to keep in the next population: keep_parents
if not (type(keep_parents) in GA.supported_int_types):
self.valid_parameters = False
raise TypeError(f"Incorrect type of the value assigned to the keep_parents parameter. The value ({keep_parents}) of type {type(keep_parents)} found but an integer is expected.")
elif (keep_parents > self.sol_per_pop or keep_parents > self.num_parents_mating or keep_parents < -1):
self.valid_parameters = False
raise ValueError(f"Incorrect value to the keep_parents parameter: {keep_parents}. \nThe assigned value to the keep_parent parameter must satisfy the following conditions: \n1) Less than or equal to sol_per_pop\n2) Less than or equal to num_parents_mating\n3) Greater than or equal to -1.")
self.keep_parents = keep_parents
if parent_selection_type == "sss" and self.keep_parents == 0:
if not self.suppress_warnings:
warnings.warn("The steady-state parent (sss) selection operator is used despite that no parents are kept in the next generation.")
# Validating the number of elitism to keep in the next population: keep_elitism
if not (type(keep_elitism) in GA.supported_int_types):
self.valid_parameters = False
raise TypeError(f"Incorrect type of the value assigned to the keep_elitism parameter. The value ({keep_elitism}) of type {type(keep_elitism)} found but an integer is expected.")
elif (keep_elitism > self.sol_per_pop or keep_elitism < 0):
self.valid_parameters = False
raise ValueError(f"Incorrect value to the keep_elitism parameter: {keep_elitism}. \nThe assigned value to the keep_elitism parameter must satisfy the following conditions: \n1) Less than or equal to sol_per_pop\n2) Greater than or equal to 0.")
self.keep_elitism = keep_elitism
# Validate keep_parents.
if self.keep_elitism == 0:
# Keep all parents in the next population.
if (self.keep_parents == -1):
self.num_offspring = self.sol_per_pop - self.num_parents_mating
# Keep no parents in the next population.
elif (self.keep_parents == 0):
self.num_offspring = self.sol_per_pop
# Keep the specified number of parents in the next population.
elif (self.keep_parents > 0):
self.num_offspring = self.sol_per_pop - self.keep_parents
else:
self.num_offspring = self.sol_per_pop - self.keep_elitism
# Check if the fitness_func is a method.
# In PyGAD 2.19.0, a method can be passed to the fitness function. If function is passed, then it accepts 2 parameters. If method, then it accepts 3 parameters.
# In PyGAD 2.20.0, a new parameter is passed referring to the instance of the `pygad.GA` class. So, the function accepts 3 parameters and the method accepts 4 parameters.
if inspect.ismethod(fitness_func):
# If the fitness is calculated through a method, not a function, then there is a fourth 'self` paramaters.
if (fitness_func.__code__.co_argcount == 4):
self.fitness_func = fitness_func
else:
self.valid_parameters = False
raise ValueError(f"In PyGAD 2.20.0, if a method is used to calculate the fitness value, then it must accept 4 parameters\n1) Expected to be the 'self' object.\n2) The instance of the 'pygad.GA' class.\n3) A solution to calculate its fitness value.\n4) The solution's index within the population.\n\nThe passed fitness method named '{fitness_func.__code__.co_name}' accepts {fitness_func.__code__.co_argcount} parameter(s).")
elif callable(fitness_func):
# Check if the fitness function accepts 2 paramaters.
if (fitness_func.__code__.co_argcount == 3):
self.fitness_func = fitness_func
else:
self.valid_parameters = False
raise ValueError(f"In PyGAD 2.20.0, the fitness function must accept 3 parameters:\n1) The instance of the 'pygad.GA' class.\n2) A solution to calculate its fitness value.\n3) The solution's index within the population.\n\nThe passed fitness function named '{fitness_func.__code__.co_name}' accepts {fitness_func.__code__.co_argcount} parameter(s).")
else:
self.valid_parameters = False
raise TypeError(f"The value assigned to the fitness_func parameter is expected to be of type function but {type(fitness_func)} found.")
if fitness_batch_size is None:
pass
elif not (type(fitness_batch_size) in GA.supported_int_types):
self.valid_parameters = False
raise TypeError(f"The value assigned to the fitness_batch_size parameter is expected to be integer but the value ({fitness_batch_size}) of type {type(fitness_batch_size)} found.")
elif fitness_batch_size <= 0 or fitness_batch_size > self.sol_per_pop:
self.valid_parameters = False
raise ValueError(f"The value assigned to the fitness_batch_size parameter must be:\n1) Greater than 0.\n2) Less than or equal to sol_per_pop ({self.sol_per_pop}).\nBut the value ({fitness_batch_size}) found.")
self.fitness_batch_size = fitness_batch_size
# Check if the on_start exists.
if not (on_start is None):
if inspect.ismethod(on_start):
# Check if the on_start method accepts 2 paramaters.
if (on_start.__code__.co_argcount == 2):
self.on_start = on_start
else:
self.valid_parameters = False
raise ValueError(f"The method assigned to the on_start parameter must accept only 2 parameters:\n1) Expected to be the 'self' object.\n2) The instance of the genetic algorithm.\nThe passed method named '{on_start.__code__.co_name}' accepts {on_start.__code__.co_argcount} parameter(s).")
# Check if the on_start is a function.
elif callable(on_start):
# Check if the on_start function accepts only a single paramater.
if (on_start.__code__.co_argcount == 1):
self.on_start = on_start
else:
self.valid_parameters = False
raise ValueError(f"The function assigned to the on_start parameter must accept only 1 parameter representing the instance of the genetic algorithm.\nThe passed function named '{on_start.__code__.co_name}' accepts {on_start.__code__.co_argcount} parameter(s).")
else:
self.valid_parameters = False
raise TypeError(f"The value assigned to the on_start parameter is expected to be of type function but {type(on_start)} found.")
else:
self.on_start = None
# Check if the on_fitness exists.
if not (on_fitness is None):
# Check if the on_fitness is a method.
if inspect.ismethod(on_fitness):
# Check if the on_fitness method accepts 3 paramaters.
if (on_fitness.__code__.co_argcount == 3):
self.on_fitness = on_fitness
else:
self.valid_parameters = False
raise ValueError(f"The method assigned to the on_fitness parameter must accept 3 parameters:\n1) Expected to be the 'self' object.\n2) The instance of the genetic algorithm.3) The fitness values of all solutions.\nThe passed method named '{on_fitness.__code__.co_name}' accepts {on_fitness.__code__.co_argcount} parameter(s).")
# Check if the on_fitness is a function.
elif callable(on_fitness):
# Check if the on_fitness function accepts 2 paramaters.