src.ch07 package

Submodules

src.ch07.c1_breed_rats module

Efficiently breed rats to an average weight of 50000 grams.

Use genetic algorithm on a mixed population of male and female rats.

class src.ch07.c1_breed_rats.BreedRats(num_males: int = 4, num_females: int = 16, target_wt: int = 50000, gen_limit: int = 500)[source]

Bases: object

Efficiently breed rats to an average weight of target_wt.

Use genetic algorithm on a mixed population of male and female rats.

Weights and number of each gender vary and can be set by modifying the following:

Parameters
  • num_males (int) – Number of male rats in population. Default is 4.

  • num_females (int) – Number of female rats in population. Default is 16.

  • target_wt (int) – Target weight in grams. Default is 50000.

  • gen_limit (int) – Generational cutoff to stop breeding program. Default is 500.

static combine_values(dictionary: dict) → list[source]

Combine dictionary values.

Combine values in a dictionary of lists into one list.

Parameters

dictionary (dict) – Dictionary of lists.

Returns

List containing all values that were in dictionary.

crossover(population: dict) → dict[source]

Crossover genes among members (weights) of a population.

Breed population where each breeding pair produces a litter of instance value for litter_sz pups. Pup’s gender is assigned randomly.

To accommodate mismatched pairs, breeding pairs are selected randomly, and once paired, females are removed from the breeding pool while males remain.

Parameters

population (dict) – Dictionary of lists with males and females as keys and specimen weight in grams as values.

Returns

Dictionary of lists with males and females as keys and pup weight in grams as values.

property female_mode_wt

Most common adult female rat weight in initial population.

Default is 250.

Type

int

property gen_limit

Generational cutoff to stop breeding program.

Default is 500.

Type

int

get_population(num_males: int = None, num_females: int = None) → dict[source]

Generate random population of rats.

Wraps populate() using num_males and num_females.

Parameters
  • num_males (int) – Number of males in population. If None, defaults to instance value.

  • num_females (int) – Number of females in population. If None, defaults to instance value.

Returns

Dictionary of lists with males and females as keys and specimen weight in grams as values.

property litter_sz

Number of pups per pair of breeding rats.

Default is 8.

Type

int

property litters_per_yr

Number of litters per year per pair of breeding rats.

Default is 10.

Type

int

property male_mode_wt

Most common adult male rat weight in initial population.

Default is 300.

Type

int

property max_wt

Maximum weight of adult rat in initial population.

Default is 600.

Type

int

measure(population: dict) → float[source]

Measure average weight of population against target.

Calculate mean weight of population and divide by target_wt to determine if goal has been met.

Parameters

population (dict) – Dictionary of lists with males and females as keys and specimen weight in grams as values.

Returns

float representing decimal percentage of completion where a value of 1 is 100%, or complete.

property min_wt

Minimum weight of adult rat in initial population.

Default is 200.

Type

int

property mut_max

Scalar on rat weight of most beneficial mutation.

Default is 1.2.

Type

float

property mut_min

Scalar on rat weight of least beneficial mutation.

Default is 0.5.

Type

float

property mut_odds

Probability of a mutation occurring in a pup.

Default is 0.01.

Type

float

mutate(litter: dict) → dict[source]

Randomly alter pup weights applying input odds as a scalar.

For each pup in litter, randomly decide if a floating point number between instance values for mut_min and mut_max from uniform will be used as a scalar to modified their weight.

Parameters

litter (dict) – Dictionary of lists with males and females as keys and specimen weight in grams as values.

Returns

Same dictionary of lists with weights potentially modified.

property num_females

Number of female rats in population.

Default is 16.

Type

int

property num_males

Number of male rats in population.

Default is 4.

Type

int

populate(pop_total: int, mode_wt: int) → list[source]

Generate population with a triangular distribution of weights.

Use triangular to generate a population with a triangular distribution of weights based on mode_wt.

Parameters
  • pop_total (int) – Total number of rats in population.

  • mode_wt (int) – Most common adult rat weight in initial population.

Returns

List of triangularly distributed weights of a given rat population.

select(population: dict) → dict[source]

Select largest members of population.

Sort members in descending order, and then keep largest members up to instance values for num_males and num_females.

Parameters

population (dict) – Dictionary of lists with males and females as keys and specimen weight in grams as values.

Returns

Dictionary of lists of specified length of largest members of population.

Examples

>>> from src.ch07.c1_breed_rats import BreedRats
>>> sample_one = BreedRats(num_males = 4, num_females = 4)
>>> s1_population = sample_one.get_population(num_males = 5,
...                                           num_females = 10)
>>> selected_population = sample_one.select(s1_population)
>>> print(selected_population)
{'males': [555, 444, 333, 222], 'females': [999, 888, 777, 666]}
simulate(population: dict) → tuple[source]

Simulate genetic algorithm by breeding rats.

Using population, repeat cycle of measure, select, crossover, and mutate until either target_wt or gen_limit are met.

Parameters

population (dict) – Dictionary of lists with males and females as keys and specimen weight in grams as values.

Returns

Tuple containing list of average weights of generations and number of generations.

Examples

>>> from src.ch07.c1_breed_rats import BreedRats
>>> sample_one = BreedRats()
>>> s1_population = sample_one.get_population()
>>> ave_wt, generations = sample_one.simulate(s1_population)
>>> print(generations)
248
property target_wt

Target weight in grams.

Default is 50000.

Type

int

src.ch07.c1_breed_rats.main()[source]

Demonstrate BreedRats class.

Use default values to run a demonstration simulation and display time (in seconds) it took to run.

src.ch07.c2_safe_cracker module

Use hill-climbing algorithm to solve a lock combination.

Solve a lock combination by randomly changing a tumbler’s values one by one and noting whether the safe had a response. If so, lock the tumbler at that value and continue randomly changing tumbler values.

Previously, a locked tumbler can still be changed, but the safe wouldn’t respond, so the change would be discarded. This improves upon the algorithm by removing the locked tumbler from the pool of tumblers to randomly change.

src.ch07.c2_safe_cracker.compare(combo: list, attempt: list) → int[source]

Compare items in two lists and count number of matches.

Compare each tumbler in combo with attempt and return the number of matches.

Parameters
  • combo (list) – Integers of safe combination.

  • attempt (list) – Integers of guessed safe combination.

Returns

Number of tumbler matches between combo and attempt.

src.ch07.c2_safe_cracker.crack_safe(combo: str) → tuple[source]

Crack a safe combination with a hill-climbing algorithm.

Solve a lock combination by randomly changing a tumbler’s values one by one and noting whether the safe had a response. If so, lock the tumbler at that value, remove it from the pool of tumblers, and continue randomly changing tumbler values.

Parameters

combo (str) – String of numbers representing combination of safe.

Returns

Tuple with string of solved combination and number of attempts.

src.ch07.c2_safe_cracker.main()[source]

Demonstrate safe cracker.

Use default combination to demonstrate crack_safe() and display time (in seconds) it took to run.

Module contents

Chapter 7.