examples/model-1.ss
#lang scheme/base
;;; Model 1 - Discrete Event Model

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

;;; Simulation Parameters
(define end-time 720.0)
(define n-pits 7)

;;; Data collection variables
(define total-ingots 0)
(define wait-time (make-variable))

;;; Model Definition
(define random-sources (make-random-source-vector 2))

(define furnace #f)
(define pit #f)

(define (scheduler)
  (let loop ()
    (schedule now (ingot))
    (wait (random-exponential (vector-ref random-sources 0) 1.5))
    (loop)))

(define-process (ingot)
  (let ((arrive-time (current-simulation-time)))
    (with-resource (pit)
      (set-variable-value! wait-time (- (current-simulation-time) arrive-time))
      (set-insert! furnace self)
      (work (random-flat (vector-ref random-sources 1) 4.0 8.0))
      (set-remove! furnace self))
    (set! total-ingots (+ total-ingots 1))))

(define (stop-sim)
  (printf "Report after ~a Simulated Hours - ~a Ingots Processed~n"
          (current-simulation-time) total-ingots)
  (printf "~n-- Ingot Waiting Time Statistics --~n")
  (printf "Mean Wait Time        = ~a~n" (variable-mean wait-time))
  (printf "Variance              = ~a~n" (variable-variance wait-time))
  (printf "Maximum Wait Time     = ~a~n" (variable-maximum wait-time))
  (printf "~n-- Furnace Utilization Statistics --~n")
  (printf "Mean No. of Ingots    = ~a~n"
          (variable-mean (set-variable-n furnace)))
  (printf "Variance              = ~a~n"
          (variable-variance (set-variable-n furnace)))
  (printf "Maximum No. of Ingots = ~a~n"
          (variable-maximum (set-variable-n furnace)))
  (printf "Minimum No. of Ingots = ~a~n"
          (variable-minimum (set-variable-n furnace)))
  (write-special
   (history-plot (variable-history (set-variable-n furnace))
                 "Furnace Utilization History"))
  (newline)
  (stop-simulation))

(define (initialize)
  (set! total-ingots 0)
  (set! wait-time (make-variable))
  (set! pit (make-resource n-pits))
  (set! furnace (make-set))
  (accumulate (variable-history (set-variable-n furnace)))
  (tally (variable-statistics wait-time))
  (schedule (at end-time) (stop-sim))
  (schedule (at 0.0) (scheduler)))

(define (run-simulation)
  (with-new-simulation-environment
    (initialize)
    (start-simulation)))

(run-simulation)