examples/closed-loop-ex1.ss
#lang scheme/base
; Closed Loop Example

(require (planet "simulation-with-graphics.ss"
                 ("williams" "simulation.plt")))
(require (planet "random-distributions.ss"
                 ("williams" "science.plt")))

(define n-attendants 2)
(define attendant #f)

(define-process (generator n)
  (do ((i 0 (+ i 1)))
      ((= i n) (void))
    (wait (random-exponential 4.0))
    (schedule now (customer i))))

(define-process (customer i)
  (with-resource (attendant)              
    (work (random-flat 2.0 10.0))))

(define (run-simulation n1 n2)
  (let ((avg-queue-length (make-variable)))
    (tally (variable-statistics avg-queue-length))
    (tally (variable-history avg-queue-length))
    (do ((i 1 (+ i 1)))
        ((> i n1) (void))
      (with-new-simulation-environment
       (set! attendant (make-resource n-attendants))
       (schedule (at 0.0) (generator n2))
       (start-simulation)
       (set-variable-value! avg-queue-length
         (variable-mean (resource-queue-variable-n attendant)))))
    (printf "--- Closed Loop Example ---~n")
    (printf "Number of attendants         = ~a~n" n-attendants)
    (printf "Number of experiments        = ~a~n"
            (variable-n avg-queue-length))
    (printf "Minimum average queue length = ~a~n"
            (variable-minimum avg-queue-length))
    (printf "Maximum average queue length = ~a~n"
            (variable-maximum avg-queue-length))
    (printf "Mean average queue length    = ~a~n"
            (variable-mean avg-queue-length))
    (printf "Variance                     = ~a~n"
            (variable-variance avg-queue-length))
    (print (history-plot (variable-history avg-queue-length)
                                 "Average Queue Length"))
    (newline)))
  
(run-simulation 1000 1000)