#NEWLINE# def mutate( self , mutation_range , mutation_rate , context ) : #NEWLINE# #INDENT# '\n        Mutates the genotypes no more than the mutation_range depending on the\n        mutation_rate given and the cantus_firmus passed in as the context (to\n        ensure the mutation is valid).\n        ' #NEWLINE# odd_beat_mutation_intervals = [ interval for interval in VALID_ODD_BEAT_INTERVALS if ( interval <= mutation_range ) ] #NEWLINE# even_beat_mutation_intervals = [ interval for interval in VALID_EVEN_BEAT_INTERVALS if ( interval <= mutation_range ) ] #NEWLINE# chromosome_length = len ( self . chromosome ) #NEWLINE# for locus in range ( chromosome_length ) : #NEWLINE# #INDENT# if ( mutation_rate >= random . random ( ) ) : #NEWLINE# #INDENT# cantus_firmus_note = context [ ( locus / 4 ) ] #NEWLINE# pitches_to_avoid = [ ] #NEWLINE# if ( locus > 0 ) : #NEWLINE# #INDENT# pre_pitch = self . chromosome [ ( locus - 1 ) ] #NEWLINE# pitches_to_avoid . append ( pre_pitch ) #NEWLINE# #UNINDENT# if ( locus < ( chromosome_length - 2 ) ) : #NEWLINE# #INDENT# post_pitch = self . chromosome [ ( locus + 1 ) ] #NEWLINE# pitches_to_avoid . append ( post_pitch ) #NEWLINE# #UNINDENT# if ( locus % 2 ) : #NEWLINE# #INDENT# mutation_intervals = [ i for i in even_beat_mutation_intervals if ( ( cantus_firmus_note + i ) not in pitches_to_avoid ) ] #NEWLINE# if ( not mutation_intervals ) : #NEWLINE# #INDENT# mutation_intervals = even_beat_mutation_intervals #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# mutation_intervals = [ i for i in odd_beat_mutation_intervals if ( ( cantus_firmus_note + i ) not in pitches_to_avoid ) ] #NEWLINE# if ( not mutation_intervals ) : #NEWLINE# #INDENT# mutation_intervals = odd_beat_mutation_intervals #NEWLINE# #UNINDENT# #UNINDENT# valid_mutation_range = [ interval for interval in mutation_intervals if ( ( interval + cantus_firmus_note ) < 17 ) ] #NEWLINE# mutation = random . choice ( valid_mutation_range ) #NEWLINE# new_allele = ( cantus_firmus_note + mutation ) #NEWLINE# self . chromosome [ locus ] = new_allele #NEWLINE# self . fitness = None