Код: Выделить всё
import numpy as np
def generate_genome(length: int, max_individuals: int = 0) -> Genome:
bits = None
if max_individuals > 0:
num_individuals = np.random.randint(1, max_individuals + 1)
print(f'Will have maximum of {num_individuals} individuals')
print('Controlled randomization')
bits = np.full(length, 0)
bits_flipped_ids = np.random.choice(range(0, length), size=num_individuals, replace=False)
print(f'Following indices will be flipped: {sorted(bits_flipped_ids)}')
np.put(a=bits, ind=bits_flipped_ids, v=1)
else:
print('Standard randomization')
bits = np.random.choice([0, 1], size=length)
genome = Genome(bits=bits.tolist())
print(f'Genome bits: {genome.bits}')
return genome
- без max_individuals — создает список битов определенной длины
- с max_individuals — создает список битов определенной длины, но также гарантирует, что количество единиц не превышает max_individuals. Размещение единиц происходит по случайным индексам (конечно, ограничено разрешенной длиной списка)
- без max_individuals
Код: Выделить всё
generate_genome(10, 0) [0 1 1 0 0 1 1 1 1 0] [1 0 1 1 1 1 0 1 1 1] [0 1 0 1 0 1 1 0 0 0] [1 1 0 0 0 1 1 0 1 1] [0 1 0 0 1 0 0 1 0 0]
- с max_individuals
Код: Выделить всё
generate_genome(10, 3) [0 0 0 0 0 0 0 0 0 1] with bits flipped at [9] [0 0 0 1 0 1 0 1 0 0] with bits flipped at [3 5 7] [0 1 0 0 0 1 0 1 0 0] with bits flipped at [1 5 7] [0 1 0 1 0 0 0 0 0 0] with bits flipped at [1 3]
ОБНОВЛЕНИЕ: Мне удалось упростить функцию генерации_генома() на основе по комментариям (спасибо!).
Код: Выделить всё
def generate_genome(length: int, max_individuals: int = 0):
# For the given length (number of bits) the maximum (where all are 1s)
# is (2^length - 1). The numpy.arange() stops at (stop - 1)
bits_all_possible = np.arange(2**length)
# Shuffle to introduce randomness
np.random.shuffle(bits_all_possible)
if max_individuals > 0:
bits_all_possible = np.array([b for b in bits_all_possible if np.bitwise_count(b)
Подробнее здесь: [url]https://stackoverflow.com/questions/79019920/how-to-generate-multiple-lists-vectors-same-length-that-are-unique-or-partiall[/url]