view/download model file: ImageHillClimber.nlogo
This model demonstrates a simple hill climbing algorithm, by doing "pixel swaps" from a scrambled image, using an objective function of either how close the image is to the original in terms rgb color difference, or in terms of pixel displacement.
Written by Forrest Stonedahl, 2009...
patches-own [ correct-rgb my-pcolors-home myerror ] to show-image import-drawing "bryan_color.png" end to hide-image cd end to setup clear-all import-pcolors-rgb "bryan_color.png" ask patches [ set correct-rgb pcolor ] let all-pcolors [] let pcolor-homes [] ask patches [ set all-pcolors fput pcolor all-pcolors set pcolor-homes fput self pcolor-homes ] set all-pcolors reverse all-pcolors set pcolor-homes reverse pcolor-homes ; let shuffled-pcolors ([pcolor] of patches) ask patches [ set pcolor first all-pcolors set all-pcolors but-first all-pcolors set my-pcolors-home first pcolor-homes set pcolor-homes but-first pcolor-homes ] do-plotting end to go ask patches [ let neighbor one-of patches if (swap-mode = "8 neighbor pixels") [ set neighbor one-of neighbors ] if (swap-mode = "within radius 5") [ set neighbor one-of patches in-radius 5 ] let current-error error-fun + [error-fun] of neighbor swap-pcolor-with neighbor let new-error error-fun + [error-fun] of neighbor if (new-error > current-error or ((not swap-when-equal?) and new-error = current-error)) [ swap-pcolor-with neighbor ] ] tick do-plotting end to swap-pcolor-with [ p2 ] let temp pcolor set pcolor [pcolor] of p2 ask p2 [ set pcolor temp ] set temp my-pcolors-home set my-pcolors-home [ my-pcolors-home ] of p2 ask p2 [ set my-pcolors-home temp ] end to-report error-fun if (error-measure = "color") [ report sum (map [(?1 - ?2) ^ 2] pcolor correct-rgb) / (256 * 2) ] report (manhattan-distance my-pcolors-home) end to-report manhattan-distance [ p2 ] report abs (pxcor - [pxcor] of p2) + abs(pycor - [pycor] of p2) end ;; ====== Plotting to do-plotting set-current-plot "Error Plot" plotxy ticks * (count patches) (sum [error-fun] of patches) end