ó
\ÿˆIc           @   sº  d  Z  d d l Z d d l Z d d l Z d d l Z d d l Z d d l m Z d d l m	 Z	 d d l
 m Z d d l m Z d d l m Z d d l m Z d d	 l m Z d
 Z d „  Z d „  Z d „  Z d „  Z d e j f d „  ƒ  YZ d d  d „  ƒ  YZ d d! d „  ƒ  YZ d d" d „  ƒ  YZ d Z e d k r¬e e j  ƒ d k rke! e j  d ƒ Z q¬e e j  ƒ d k r¬d GHd GHd GHd GHd GHe j" d ƒ q¬n  e e ƒ d S(#   sr  Try out the N-queens problem for an arbitrary number of queens.

This program uses Genetic Algorithms to try to solve the N queens
problem, in which you place N different queens on an N by N chess
board such that no two queens will be attacking each other.

We represent queens on the board as a tuple like (1, 2, 3, 4, 5)
which would be 5 queens diaganol across the board.

Usage:
python test_GAQueens.py <Number of Queens to place>

where <Number of Queens to place> is just a number specifying how many
queens you want to try to calculate this for.

When called as part of the Biopython unit test suite, 5 queens are used.
iÿÿÿÿN(   t   Alphabet(   t   GenerationEvolver(   t   Organism(   t   ConversionMutation(   t   SinglePointCrossover(   t   RouletteWheelSelection(   t   TournamentSelectioni    c         C   sV  d |  GHd } d | GHt  |  ƒ } t j | |  | t ƒ } d GHt d d ƒ } t t d d d	 d
 ƒ} t ƒ  } t | | | d ƒ } t j	 t j ƒ  ƒ } t
 | | ƒ }	 |	 j t ƒ }
 t j	 t j ƒ  ƒ } g  } x< |
 D]4 } | j |  k rÛ | | k r| j | ƒ qqÛ qÛ Wt rRd | | f GHx' | D] } d G| GHt | j ƒ q/Wn  d  S(   Ns   Calculating for %s queens...iè  s3   Generating an initial population of %s organisms...s7   Evolving the population and searching for a solution...t   mutation_rategš™™™™™©?t   crossover_probgš™™™™™É?t   max_crossover_sizei   i   s$   Search started at %s and ended at %ss
   We did it!(   t   QueensAlphabetR   t   random_populationt   queens_fitnesst   QueensMutationt   QueensCrossovert   QueensRepairR   t   timet   ctimeR   t   evolvet   queens_solvedt   fitnesst   appendt   VERBOSEt   display_boardt   genome(   t
   num_queenst   num_orgst   queen_alphabett   start_populationt   mutatort	   crossovert   repairt
   t_selectort
   start_timet   evolvert   evolved_popt   end_timet   unique_solutionst   organism(    (    s   test_GAQueens.pyt   main(   s4    					c         C   s€   d d t  |  ƒ d GHxK t t  |  ƒ ƒ D]7 } d Gx% |  D] } | | k rT d Gq; d Gq; Wd GHq* Wd d t  |  ƒ d GHd S(   s¦   Display a genome in the N-queens problem.

    Inspired by the display function in the queens.py solution to the N-queens
    problem in the Python demo scripts.
    s   +-s   --t   +t   |t   Qt   .N(   t   lent   range(   R   t   rowt   genome_item(    (    s   test_GAQueens.pyR   N   s    	c         C   s1   x* |  D]" } | j  t | j ƒ k r d Sq Wd S(   sú   Determine if we have solved the problem.

    We just search through the population for an organism that has a
    fitness that is equal to the number of queens in the population.
    If so, we have a solution, otherwise we need to keep looking.
    i   i    (   R   R,   R   (   t	   organismst   org(    (    s   test_GAQueens.pyR   a   s    c         C   sÌ   d } x¿ t  t |  ƒ ƒ D]« } d } x‰ t  t |  ƒ ƒ D]u } | | k r8 t |  | ƒ } t |  | ƒ } | | k r€ d } Pq­ t | | ƒ t | | ƒ k r­ d } Pq­ q8 q8 W| s | d 7} q q W| S(   sè   Calculate the fitness of an organization of queens on the chessboard.

    Arguments:

    o genome -- A MutableSeq object specifying an organism genome.

    The number returned is the number of unattacked queens on the board.
    i    i   (   R-   R,   t   intt   abs(   R   R   t   check_queen_colt   is_attackedt   other_queen_colt   check_queen_rowt   other_queen_row(    (    s   test_GAQueens.pyR   o   s"    	R
   c           B   s   e  Z d  „  Z RS(   c         C   s4   g  |  _  x$ t | ƒ D] } |  j  j | ƒ q Wd S(   sE   Initialize with the number of queens we are calculating for.
        N(   t   lettersR-   R   (   t   selfR   t   num(    (    s   test_GAQueens.pyt   __init__•   s    	(   t   __name__t
   __module__R<   (    (    (    s   test_GAQueens.pyR
   ”   s   R   c           B   s5   e  Z d  Z d d „ Z d „  Z d „  Z d „  Z RS(   s+  A repair function to help create correct N-Queens solutions.

    This attempts to help generate correct solutions by offering some
    amount of repair to remove queens that are located in the same rows.
    After repair, a sequence should have no queens in the same row.

    So, if you start with something infeasible like (1, 2, 2, 3, 3, 4),
    after running it through repair you'll get a feasible individual
    like (1, 2, 5, 3, 6, 4). This should greatly reduce the number of
    individuals that need to be searched through in a population.
    i   c         C   s   | |  _  d S(   s¡   Initialize the repairer.

        Arguments:

        o repair_prob -- The probability that we'll repair a genome.
        By default, we always repair.
        N(   t   _repair_prob(   R:   t   repair_prob(    (    s   test_GAQueens.pyR<   ª   s    c         C   sL   g  } x? | j  j D]1 } | j t | ƒ ƒ d k r | j | ƒ q q W| S(   s&  Return all of the letters in the genome that are duplicated.

        This checks every letter in the genome (which are the rows of
        the chessboard, in this case), and adds them to a list of duplicated
        items if there is more than one of them, and then returns this list.
        i   (   t   alphabetR9   t   countt   strR   (   R:   R   t
   duplicatest   item(    (    s   test_GAQueens.pyt   _get_duplicates´   s
    c         C   sL   g  } x? | j  j D]1 } | j t | ƒ ƒ d k r | j | ƒ q q W| S(   sÉ   Return all of the letters in the genome which are unused.

        This checks the letters in the genome (which are th rows on the
        chessboard) and returns all items which are not used.
        i    (   RA   R9   RB   RC   R   (   R:   R   t   unusedRE   (    (    s   test_GAQueens.pyt   _get_unusedÂ   s
    c         C   s³   t  j  ƒ  } | |  j k r¯ x‘ |  j | j ƒ } t | ƒ d k rF Pn  | j j | d ƒ } |  j | j ƒ } t | ƒ d k sŒ t d ƒ ‚ t  j | ƒ } | | j | <q Wn  | S(   s§   Repair the specified genome to make it feasible.

        Arguments:

        o organism -- The Organism object we are going to perform the
        repair on.
        i    s   Unexpected lack of empty rows(	   t   randomR?   RF   R   R,   t   indexRH   t   AssertionErrort   choice(   R:   R&   t   repair_chancet   duplicated_itemst   duplicated_post	   free_rowst   new_item(    (    s   test_GAQueens.pyR   Ï   s    	(   R=   R>   t   __doc__R<   RF   RH   R   (    (    (    s   test_GAQueens.pyR   ž   s
   
		R   c           B   s2   e  Z d  Z d d d „ Z d „  Z d d „ Z RS(   s±  Crossover operation to help in solving the N-Queens problem.

    This tries to perform smarter crossovers by picking out regions of
    the genome that have high fitness.

    It scans through both genomes in the crossover with a window half the
    size of the genome, and finds the region with the highest fitness in
    both genomes. It then recombines these high fitness windows to form
    the new genome that is returned.
    gš™™™™™¹?i   c         C   s   | |  _  | |  _ | |  _ d S(   sy  Initialize to do N-Queens optimized crossover.

        Arguments:

        o fitness_func -- A function that can calculate the fitness of
        a genome.

        o crossover_prob -- The probability of having a crossover
        between two passed in organisms.

        o max_crossover_size -- The maximum crossover size of the 'best' region
        to search for.
        N(   t   _crossover_probt   _fitness_calct   _max_crossover_size(   R:   t   fitness_funcR   R	   (    (    s   test_GAQueens.pyR<   ø   s    		c   
      C   sÎ   | j  ƒ  } | j  ƒ  } t j ƒ  } | |  j k rÄ |  j | j d d ƒ\ } } |  j | j d d ƒ\ } }	 t | ƒ t | ƒ t | ƒ t |	 ƒ k s§ t d ƒ ‚ | | | _ | |	 | _ n  | | f S(   s3   Perform a crossover between two organisms.
        t   make_best_largeri   i    s   Did not preserve genome length!(   t   copyRI   RS   t   _find_best_regionR   R,   RK   (
   R:   t   org_1t   org_2t	   new_org_1t	   new_org_2t   crossover_chancet   best_1t   rest_1t   best_2t   rest_2(    (    s   test_GAQueens.pyt   do_crossover  s    /	i   c         C   sÿ   t  t | ƒ d |  j ƒ } t | ƒ | } | rD t  | | ƒ } n t | | ƒ } d d d g } x^ t t | ƒ | ƒ D]F } |  j | | | | !ƒ } | | d k ry | | | | g } qy qy W| | d | d !}	 | d | d !| | d }
 |	 |
 f S(   sŸ  Find the best region in the given genome.

        Arguments:

        o genome -- A MutableSeq object specifying the genome of an organism

        o make_best_larger -- A flag to determine whether the best region
        we should search for should be the larger region of the split
        caused by crossover or the smaller region. This makes it easy
        to split two genomes, recombine them, and get a solution that
        makes sense.

        Returns:
        o Two MutableSeq objects. They are both half of the size of the passed
        genome. The first is the highest fitness region of the genome and the
        second is the rest of the genome.
        i   i    iÿÿÿÿi   (   t   maxR,   RU   t   minR-   RT   (   R:   R   RW   t   first_regiont   second_regiont   region_sizet   best_fitnesst   start_indext   region_fitnesst   best_regiont   rest_region(    (    s   test_GAQueens.pyRY   "  s    
(   R=   R>   RR   R<   Rc   RY   (    (    (    s   test_GAQueens.pyR   í   s
   
	R   c           B   s#   e  Z d  Z d d „ Z d „  Z RS(   sW  Mutation operation to help in the N-Queens problem.

    This performs mutation, but instead of randomly mutating a single
    item to any other, it tries to mutate it to a row that is not already
    taken at some other position in the genome. This thus tries to
    generate more 'correct' mutations that will help achieve the solution.
    gü©ñÒMbP?c         C   s   | |  _  d S(   sš   Inititialize a mutator.

        Arguments:

        o mutation_rate -- The change of a mutation happening at any
        position in the genome.
        N(   t   _mutation_rate(   R:   R   (    (    s   test_GAQueens.pyR<   Z  s    c         C   så   | j  ƒ  } | j j j } xÃ t t | j ƒ ƒ D]¬ } t j ƒ  } | |  j k r1 t  j  | j j j ƒ } x- | j D]" } | | k rt | j | ƒ qt qt Wt | ƒ d k r¾ | j j j } n  t j	 | ƒ } | | j | <q1 q1 W| S(   s@   Mutate the genome trying to put in 'helpful' mutations.
        i    (
   RX   R   RA   R9   R-   R,   RI   Rn   t   removeRL   (   R:   R&   t   new_orgt   gene_choicest
   gene_indext   mutation_chancet   genet
   new_letter(    (    s   test_GAQueens.pyt   mutated  s    (   R=   R>   RR   R<   Rv   (    (    (    s   test_GAQueens.pyR   R  s   
i   t   __main__i   i   s   Usage:s4   python test_GAQueens.py <Number of Queens to place>
s:   where <Number of Queens to place> is an optional parameters7   specifying how many queens you want to try to calculates5   this for. The default number of queens to place is 5.(    (    (    (#   RR   t   syst   mathRI   RX   R   t   BioR    t   Bio.GA.EvolverR   t   Bio.GAR   t   Bio.GA.Mutation.SimpleR   t   Bio.GA.Crossover.PointR   t   Bio.GA.Selection.RouletteWheelR   t   Bio.GA.Selection.TournamentR   R   R'   R   R   R   R
   R   R   R   R   R=   R,   t   argvR2   t   exit(    (    (    s   test_GAQueens.pyt   <module>   sB   	&			%
Oe/