Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Deterministic multistage Beverton-Holt model using nested for loops in Racket
#lang racket/base
;; scalar constants
(define years 30)
(define prop-female 0.5)
(define egg-surv 0.6)
;; age-specific fecundity and survival
(define fecundity #(0 0 200 400 800))
(define survival #(0.2 0.4 0.6 0.8 0))
(define capacity #(1e6 1e5 1e4 1e3 1e2))
;; multistage Beverton-Holt model
(define (beverton-holt N p c)
(/ N (+ (/ 1 p) (/ N c))))
;; initialize empty results "matrix"
(define results (for/vector ([i (in-range years)]) (make-vector (vector-length fecundity) 0)))
;; initialize abundances in first year to arbitrary non-zero value
(vector-set! results 0 (make-vector (vector-length fecundity) 10))
;; iterate over results to fill "matrix"
(for* ([i (in-range (sub1 years))]
[j (in-range (vector-length fecundity))])
;; current abundance vector
(define N (vector-ref results i))
;; next year abundance vector
(define Nt (vector-ref results (add1 i)))
;; reproduction
(define fecundity-age-j (vector-ref fecundity j))
(when (> fecundity-age-j 0) ;; not all age classes reproduce
(define N-female (* (vector-ref N j) prop-female))
;; next year age-0
(define Nt-age-0 (vector-ref Nt 0))
(define new-age-0 (beverton-holt
(* fecundity-age-j egg-surv)
(- (vector-ref capacity 0) Nt-age-0)))
(vector-set! Nt 0 (+ Nt-age-0 new-age-0))
;; survival
(define survival-age-j (vector-ref survival j))
(when (> survival-age-j 0)
(define Nt-age-j (vector-ref Nt (add1 j)))
(define new-age-j (beverton-holt
(vector-ref N j)
(- (vector-ref capacity (add1 j)) Nt-age-j)))
(vector-set! Nt (add1 j) (+ Nt-age-j new-age-j))
(vector-set! results (add1 i) Nt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment