Starter program for a Genetic Algorithm simulation
Step 1: Generate 1 population and choose individuals to survive
Also - print the chart with individuals and statistics
(defvar *ninputs* 4)
(defclass individual ()
((chromosome :accessor individual-chrom :initarg :chromosome)
(strength :accessor individual-strength)
(strengthSqr :accessor individual-strengthSqr)
(actualCount :accessor individual-actualCount :initform 0)
)
)
(defclass population ()
((individuals :accessor population-individuals)
(popsize :accessor population-popsize)
(sumfitness :accessor population-sumfitness)
(avgfitness :accessor population-avgfitness)
(maxfitness :accessor population-maxfitness)
(pselect :accessor population-pselect)
(expectedcount :accessor population-expectedcount)
)
)
(defun makePopulation ()
"Returns its arguments in an array."
(let ((population (make-array (list *ninputs*)
:element-type 'individual))
(tempList nil) )
(dotimes (n *ninputs*)
(setf tempList (generateOneList))
(setf (aref population n) (make-instance 'individual))
(setf (individual-chrom (aref population n)) tempList)
(setf (individual-strength (aref population n))
(evaluate tempList) )
(setf (individual-strengthSqr (aref population n))
(sqr (individual-strength (aref population n))) )
)
population
)
)
(defun sqr (n)
(* n n) )
(defun printStats (popClass)
(let ((pop nil)
(sumfitness 0)
(avgfitness 0)
(maxfitness 0)
(pselectLst nil)
(expectedCountLst nil)
)
(format t "~%")
(format t "String Initial pselect expected Actual~%")
(format t "No. Population x Value f(x) f(x)/sum f(x)/avg~%")
(format t "-------------------------------------------------------------~%")
(format t "-----------------------------------------------------------~%")
(format t "Sum ~5D~%" sumfitness)
(format t "Average ~5F~%" avgfitness)
(format t "Max ~5D~%" maxfitness)
)
)
(defun generateOneList (&optional (len 5))
)
(defun makeStats (tempPop)
)
(defun select (popsize sumfitness popClass)
(let ((rand (* (random 1.0) sumfitness))
(partsum 0)
(pop nil)
)
(setf pop (population-individuals popClass))
(setf partsum (individual-strengthSqr (aref pop 0)))
(do ((j 0))
((or (= j (1- popsize)) (>= partsum rand)) j)
(setf j (1+ j))
(setf partsum (+ partsum (individual-strengthSqr
(aref pop j))))
)
)
)
(defun testGA ()
(let ((tempPop nil)
(pop nil)
)
(setf tempPop (makePopulation)) ;; makePopulation returns
;; an array of individuals.
;; This is an array of
;; class individual.
(setf pop (make-instance 'population))
(setf pop (makeStats tempPop) ) ;; makeStats returns a
;; class population
(printStats pop)
)
)
(testGA)