-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpmf.lisp
More file actions
71 lines (53 loc) · 2.12 KB
/
Copy pathpmf.lisp
File metadata and controls
71 lines (53 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
;;;; Martin Kersner, m.kersner@gmail.com
;;;; 2017/06/04
;;;;
;;;; Common Lisp version of Think Bayes
;;;; https://github.com/AllenDowney/ThinkBayes
;;;;
;;;; PROBABILITY MASS FUNCTION
(defclass probability-mass-function ()
((values :accessor get-val-prob
:initform (make-hash-table :test 'equal))))
;;; Originally called "set" in Think Bayes
(defgeneric set-value (pmf value probability)
(:documentation ""))
(defmethod set-value ((pmf probability-mass-function) value probability)
(setf (gethash value (get-val-prob pmf)) probability))
(defgeneric incr (pmf value increment)
(:documentation ""))
(defmethod incr ((pmf probability-mass-function) value increment)
(multiple-value-setq (prob pred) (gethash value (get-val-prob pmf)))
(if pred
(setf (gethash value (get-val-prob pmf)) (+ prob increment))))
(defgeneric mult (pmf value multiplier)
(:documentation ""))
(defmethod mult ((pmf probability-mass-function) value multiplier)
(multiple-value-setq (prob pred) (gethash value (get-val-prob pmf)))
(if pred
(setf (gethash value (get-val-prob pmf)) (* prob multiplier))))
(defgeneric total (pmf)
(:documentation ""))
(defmethod total ((pmf probability-mass-function))
(let ((prob-lst '()))
(maphash #'(lambda (val prob) (push prob prob-lst)) (get-val-prob pmf))
(apply '+ prob-lst)))
(defgeneric normalize (pmf &optional fraction)
(:documentation "fraction: what the total should be after normalization"))
(defmethod normalize ((pmf probability-mass-function) &optional (fraction 1.0))
(let* ((prob-sum (total pmf))
(factor (/ fraction prob-sum)))
(maphash #'(lambda (val prob)
(setf (gethash val (get-val-prob pmf)) (* prob factor)))
(get-val-prob pmf))))
(defgeneric prob (pmf prob)
(:documentation ""))
(defmethod prob ((pmf probability-mass-function) value)
(multiple-value-setq (prob pred) (gethash value (get-val-prob pmf)))
(if pred
prob
nil))
(defgeneric cdf (pmf)
(:documentation ""))
(defmethod cdf ((pmf probability-mass-function))
(make-instance 'cumulative-distribution-function
:pmf (get-val-prob pmf)))