<s> import numpy <EOL> def find_threshold ( map_data , land_percentage , ocean = None ) : <EOL> height , width = map_data . shape <EOL> mask = numpy . ma . array ( map_data , mask = False , keep_mask = True ) <EOL> if ocean is not None : <EOL> if ocean . shape != map_data . shape : <EOL> raise Exception ( <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" % ( <EOL> width , height , ocean . shape [ <NUM_LIT:1> ] , ocean . shape [ <NUM_LIT:0> ] ) ) <EOL> mask = numpy . ma . array ( mask , mask = ocean , keep_mask = True ) <EOL> def count ( e ) : <EOL> return numpy . ma . masked_less_equal ( mask , e ) . count ( ) <EOL> def search ( a , b , desired ) : <EOL> if ( not type ( a ) == int ) or ( not type ( b ) == int ) : <EOL> raise Exception ( "<STR_LIT>" ) <EOL> if a == b : <EOL> return a <EOL> if ( b - a ) == <NUM_LIT:1> : <EOL> ca = count ( a ) <EOL> cb = count ( b ) <EOL> dista = abs ( desired - ca ) <EOL> distb = abs ( desired - cb ) <EOL> if dista < distb : <EOL> return a <EOL> else : <EOL> return b <EOL> m = int ( ( a + b ) / <NUM_LIT:2> ) <EOL> cm = count ( m ) <EOL> if desired < cm : <EOL> return search ( m , b , desired ) <EOL> else : <EOL> return search ( a , m , desired ) <EOL> all_land = mask . count ( ) <EOL> desired_land = all_land * land_percentage <EOL> return search ( <NUM_LIT:0> , <NUM_LIT:255> , desired_land ) <EOL> def find_threshold_f ( map_data , land_perc , ocean = None , max = <NUM_LIT> , mindist = <NUM_LIT> ) : <EOL> height , width = map_data . shape <EOL> mask = numpy . ma . array ( map_data , mask = False , keep_mask = True ) <EOL> if ocean is not None : <EOL> if ocean . shape != map_data . shape : <EOL> raise Exception ( <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" % ( <EOL> width , height , ocean . shape [ <NUM_LIT:1> ] , ocean . shape [ <NUM_LIT:0> ] ) ) <EOL> mask = numpy . ma . array ( mask , mask = ocean , keep_mask = True ) <EOL> def count ( e ) : <EOL> return numpy . ma . masked_less_equal ( mask , e ) . count ( ) <EOL> def search ( a , b , desired ) : <EOL> if a == b : <EOL> return a <EOL> if abs ( b - a ) < mindist : <EOL> ca = count ( a ) <EOL> cb = count ( b ) <EOL> dista = abs ( desired - ca ) <EOL> distb = abs ( desired - cb ) <EOL> if dista < distb : <EOL> return a <EOL> else : <EOL> return b <EOL> m = ( a + b ) / <NUM_LIT> <EOL> cm = count ( m ) <EOL> if desired < cm : <EOL> return search ( m , b , desired ) <EOL> else : <EOL> return search ( a , m , desired ) <EOL> all_land = mask . count ( ) <EOL> desired_land = all_land * land_perc <EOL> return search ( - <NUM_LIT:1> * max , max , desired_land ) </s>
