#NEWLINE# def crowding_replacement( random , population , parents , offspring , args ) : #NEWLINE# #INDENT# 'Performs crowding replacement as a form of niching.\n    \n    This function performs crowding replacement, which means that\n    the members of the population are replaced one-at-a-time with\n    each of the offspring. A random sample of `crowding_distance`\n    individuals is pulled from the current population, and the\n    closest individual to the current offspring (where "closest"\n    is determined by the `distance_function`) is replaced by that\n    offspring, if the offspring is better. It is possible for one \n    offspring to replace an earlier offspring in the same generation, \n    given the random sample that is taken of the current survivors \n    for each offspring.\n    \n    .. Arguments:\n       random -- the random number generator object\n       population -- the population of individuals\n       parents -- the list of parent individuals\n       offspring -- the list of offspring individuals\n       args -- a dictionary of keyword arguments\n\n    Optional keyword arguments in args:    \n    \n    - *distance_function* -- a function that accepts two candidate \n      solutions and returns the distance between them (default \n      Euclidean L2 distance)\n    - *crowding_distance* -- a positive integer representing the \n      number of closest solutions to consider as a "crowd" (default 2)\n       \n    ' #NEWLINE# def distance( x , y ) : #NEWLINE# #INDENT# return math . sqrt ( sum ( [ ( ( a - b ) ** 2 ) for ( a , b ) in zip ( x , y ) ] ) ) #NEWLINE# #UNINDENT# try : #NEWLINE# #INDENT# distance_function = args [ 'distance_function' ] #NEWLINE# #UNINDENT# except KeyError : #NEWLINE# #INDENT# distance_function = distance #NEWLINE# args [ 'distance_function' ] = distance_function #NEWLINE# #UNINDENT# crowding_distance = args . setdefault ( 'crowding_distance' , 2 ) #NEWLINE# survivors = population #NEWLINE# for o in offspring : #NEWLINE# #INDENT# pool = random . sample ( survivors , crowding_distance ) #NEWLINE# closest = min ( pool , key = ( lambda x : distance_function ( o . candidate , x . candidate ) ) ) #NEWLINE# if ( o > closest ) : #NEWLINE# #INDENT# survivors . remove ( population ) #NEWLINE# survivors . append ( o ) #NEWLINE# #UNINDENT# #UNINDENT# return survivors