summaryrefslogtreecommitdiff
path: root/services/nnls.rkt
blob: 40f03ab95162f493a784cff646745cdb0ea60bfd (plain)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#lang racket

(provide find-ferti-recipe)

(require math/array
         math/matrix
         "../models/nutrient.rkt"
         "../models/nutrient-measurement.rkt"
         "../models/nutrient-target.rkt"
         "../models/fertilizer-product.rkt")

(define (find-ferti-recipe)
  (define fertilizers (get-fertilizer-products))
  (define solution-array (solve-nnls fertilizers))
  (for/list ([fertilizer (in-list fertilizers)]
             [quantity (in-array solution-array)])
    (cons fertilizer quantity)))

(define (solve-nnls fertilizers)
  (define nutrients (get-nutrients))
  (define fertilizer-product-matrix (get-fertilizer-product-matrix nutrients fertilizers))
  (define deficits
    (->col-matrix (for/list ([n nutrients])
                    (define latest-measurement (get-latest-nutrient-measurement-value n))
                    (define latest-target (get-latest-nutrient-target-value n))
                    (define deficit
                      (cond
                        [(false? latest-target) 0]
                        [(or (false? latest-measurement) (zero? latest-measurement)) latest-target]
                        [(and (number? latest-measurement) (number? latest-target))
                         (* 100 (/ (- latest-target latest-measurement) latest-measurement))]))
                    deficit)))
  (define error-threshold 10e-4)
  (lawson-hanson-1974 fertilizer-product-matrix deficits error-threshold))

;; Algorithm lifted from the Wikipedia article on NNLS
(define (lawson-hanson-1974 A y ε)
  ;;;;;;;;;
  ;; Inputs
  ;;;;;;;;;

  (-> matrix? ; Real-valued matrix A of dimension m × n
      col-matrix? ; Real-valued column matrix (vector) y of dimension m
      real? ; Real-value ɛ, tolerance for the stopping criterion
      col-matrix?) ; Real-valued solution column matrix x
  (define-values (m ; Number of nutrients
                  n) ; Number of fertilizer products
    (matrix-shape A))

  ;;;;;;;;;;;;;
  ;; Initialize
  ;;;;;;;;;;;;;

  ;; The passive set P is initially empty.
  (define P (mutable-set))
  ;; The active set R initially contains the indexes to the nutrients allowed to be...
  (define R (list->mutable-set (range n)))

  (define (colv-ref v i)
    (matrix-ref v i 0))

  ;; Gradient-like vector for residual error.
  (define (compute-w x)
    (matrix* (matrix-transpose A) (matrix- y (matrix* A x))))

  ;; max over j in R of w_j.
  (define (max-w-in-R w)
    (if (set-empty? R)
        (values -inf.0 #f)
        (let ([max-j (argmax (λ (j) (colv-ref w j)) (set->list R))])
          (values (colv-ref w max-j) max-j))))

  ;; Build full candidate vector s from current P:
  ;; s_P = (A_Pᵀ A_P)⁻¹ A_Pᵀ y, s_R = 0
  (define (make-s-from-P)
    (if (set-empty? P)
        (make-matrix n 1 0)
        (let* ([idxs (sort (set->list P) <)]
               [AP (submatrix A (::) idxs)]
               [sP (matrix* (matrix-inverse (matrix* (matrix-transpose AP) AP))
                            (matrix-transpose AP)
                            y)])
          ;; map: column index j in P -> corresponding sP entry
          (define mapping
            (for/list ([j idxs]
                       [k (in-naturals)])
              (cons j (colv-ref sP k))))
          (define (s-at i)
            (define p (assoc i mapping))
            (if p
                (cdr p)
                0))
          (build-matrix n 1 (λ (i j) (s-at i))))))

  ;; The "first try" x represents no addition of any fertilizer.
  (define x (make-matrix n 1 0))

  ;;;;;;;;;;;;;
  ;; Outer loop
  ;;;;;;;;;;;;;

  (let outer-loop ()
    (define w (compute-w x))

    (cond
      ;; If no remaining candidates in R, we're done.
      [(set-empty? R) x]

      [else
       (define-values (max-val j*) (max-w-in-R w))

       ;; Stopping criterion: max(w_R) <= ε
       (cond
         [(or (not j*) (<= max-val ε)) x]

         [else
          ;; Add j* to P, remove from R
          (set-remove! R j*)
          (set-add! P j*)

          ;; Inner loop: adjust until s_P > 0
          (let inner-loop ()
            (define s (make-s-from-P))
            (define min-sP
              (if (set-empty? P)
                  +inf.0
                  (for/fold ([mn +inf.0]) ([j (in-set P)])
                    (min mn (colv-ref s j)))))
            (cond
              ;; If all s_P > 0 (or P empty), accept s as new x and go back to outer loop
              [(or (set-empty? P) (> min-sP 0))
               (set! x s)
               (outer-loop)]

              [else
               ;; Compute α = min_{i in P, s_i <= 0} x_i / (x_i - s_i)
               (define α
                 (for/fold ([a +inf.0]) ([j (in-set P)])
                   (define sj (colv-ref s j))
                   (if (<= sj 0)
                       (let* ([xj (colv-ref x j)]
                              [den (- xj sj)])
                         (if (> den 0)
                             (min a (/ xj den))
                             a))
                       a)))

               (when (or (equal? α +inf.0) (<= α 0))
                 (error 'lawson-hanson-1974 "no valid α in inner loop"))

               ;; x ← x + α (s − x)
               (define new-x (matrix+ x (matrix-scale (matrix- s x) α)))

               ;; Move to R all indices j in P with x_j <= 0
               (define to-remove '())
               (for ([j (in-set P)])
                 (when (<= (colv-ref new-x j) 0)
                   (set! to-remove (cons j to-remove))))
               (for ([j to-remove])
                 (set-remove! P j)
                 (set-add! R j))

               (set! x new-x)
               (inner-loop)]))])])))

(define (get-fertilizer-product-matrix nutrients fertilizers)
  ;; Lines are nutrients, columns are fertilizers
  (build-matrix (length nutrients)
                (length fertilizers)
                (λ (i j)
                  (define selected-nutrient (list-ref nutrients i))
                  (define product (list-ref fertilizers j))
                  (hash-ref (fertilizer-product-values product) selected-nutrient 0))))

(module+ test
  (require rackunit
           rackunit/text-ui
           "../db/conn.rkt"
           "../db/migrations.rkt")

  (define test-date "2025-01-01")

  (run-tests (test-suite "NNLS"
               (test-case "Build fertilizer product matrix"
                 (connect! #:path 'memory)
                 (migrate-all!)

                 (define n1 (create-nutrient! "N1" "N1"))
                 (define n2 (create-nutrient! "N2" "N2"))
                 (define nutrients (list n1 n2))

                 (define f1 (create-fertilizer-product! "F1" "F1" (hash n1 10 n2 20)))
                 (define f2 (create-fertilizer-product! "F2" "F2" (hash n1 30 n2 5)))
                 (define fertilizers (list f1 f2))

                 (define matrix (get-fertilizer-product-matrix nutrients fertilizers))

                 (check-= (matrix-ref matrix 0 0) 10 0 "N1 in F1")
                 (check-= (matrix-ref matrix 0 1) 30 0 "N1 in F2")
                 (check-= (matrix-ref matrix 1 0) 20 0 "N2 in F1")
                 (check-= (matrix-ref matrix 1 1) 5 0 "N2 in F2")

                 (disconnect!))

               (test-case "Single nutrient, single fertilizer"
                 (define A (matrix [[2]]))
                 (define y (col-matrix [10]))
                 (define ε 1e-6)

                 (define result (lawson-hanson-1974 A y ε))

                 (check-= (matrix-ref result 0 0) 5.0 ε "Should give x = 5 since 2*5 = 10"))

               (test-case "Two variables, known solution"
                 (define A (matrix [[1 0] [0 1]]))
                 (define y (col-matrix [3 4]))
                 (define ε 1e-6)

                 (define result (lawson-hanson-1974 A y ε))

                 (check-= (matrix-ref result 0 0) 3.0 ε "x1 should be 3")
                 (check-= (matrix-ref result 1 0) 4.0 ε "x2 should be 4"))

               (test-case "Overdetermined system"
                 (define A (matrix [[1 1] [2 1] [1 2]]))
                 (define y (col-matrix [3 5 5]))
                 (define ε 1e-4)

                 (define result (lawson-hanson-1974 A y ε))

                 ;; Solution should be approximately [1.636, 1.636] (least squares fit)
                 (check-= (matrix-ref result 0 0) 1.636 0.01 "x1 approximately 1.636")
                 (check-= (matrix-ref result 1 0) 1.636 0.01 "x2 approximately 1.636"))

               (test-case "Non-negativity enforcement"
                 (define A (matrix [[1 -1] [1 1]]))
                 (define y (col-matrix [1 3]))
                 (define ε 1e-6)

                 (define result (lawson-hanson-1974 A y ε))

                 ;; All results should be non-negative
                 (check-true (>= (matrix-ref result 0 0) 0) "x1 should be non-negative")
                 (check-true (>= (matrix-ref result 1 0) 0) "x2 should be non-negative"))

               (test-case "Zero target"
                 (define A (matrix [[1 2] [3 4]]))
                 (define y (col-matrix [0 0]))
                 (define ε 1e-6)

                 (define result (lawson-hanson-1974 A y ε))

                 (check-= (matrix-ref result 0 0) 0.0 ε "x1 should be 0")
                 (check-= (matrix-ref result 1 0) 0.0 ε "x2 should be 0"))

               (test-case "Ferti recipe"
                 (connect! #:path 'memory)
                 (migrate-all!)

                 (define nitrogen (create-nutrient! "Nitrogen" "N"))
                 (define phosphorus (create-nutrient! "Phosphorus" "P"))

                 (create-nutrient-measurement! test-date (hash nitrogen 0 phosphorus 0))
                 (create-nutrient-target! test-date (hash nitrogen 100 phosphorus 50))

                 (create-fertilizer-product! "Nitrogen" "King Nitrogen" (hash nitrogen 100))
                 (create-fertilizer-product! "Phosphorus"
                                             "Phosphorescent Baboon"
                                             (hash nitrogen 10 phosphorus 100))
                 (create-fertilizer-product! "Diluted phosphorus"
                                             "John's Phosphorus"
                                             (hash nitrogen 3 phosphorus 30))

                 (define recipe (find-ferti-recipe))

                 (check-equal? (length recipe) 3 "Should have 3 fertilizer products")

                 (for ([pair recipe])
                   (check-true (>= (cdr pair) 0) "Fertilizer quantity should be non-negative"))

                 (disconnect!))

               ;; Test deficit calculation edge cases
               (test-case "Deficit calculation with missing data"
                 (connect! #:path 'memory)
                 (migrate-all!)

                 (define n (create-nutrient! "TestNutrient" "TN"))

                 ;; No measurement, no target
                 (check-false (get-latest-nutrient-measurement-value n))
                 (check-false (get-latest-nutrient-target-value n))

                 ;; Add only target
                 (create-nutrient-target! test-date (hash n 100))
                 (check-= (get-latest-nutrient-target-value n) 100 0)

                 ;; Add measurement
                 (create-nutrient-measurement! test-date (hash n 50))
                 (define measured (get-latest-nutrient-measurement-value n))
                 (define targeted (get-latest-nutrient-target-value n))

                 ;; Deficit should be 100% (from 50 to 100)
                 (define deficit (* 100 (/ (- targeted measured) measured)))
                 (check-= deficit 100.0 0.01 "Deficit should be 100%")

                 (disconnect!))

               ;; Test recipe with realistic constraints
               (test-case "Recipe calculation with real-world scenario"
                 (connect! #:path 'memory)
                 (migrate-all!)

                 (define n (create-nutrient! "N" "N"))
                 (define p (create-nutrient! "P" "P"))
                 (define k (create-nutrient! "K" "K"))

                 ;; Current levels
                 (create-nutrient-measurement! test-date (hash n 50 p 10 k 100))

                 ;; Target levels
                 (create-nutrient-target! test-date (hash n 150 p 30 k 200))

                 ;; Fertilizers with different NPK ratios
                 (create-fertilizer-product! "" "Balanced" (hash n 100 p 100 k 100))
                 (create-fertilizer-product! "Nitrogen blend" "High-N" (hash n 200 p 50 k 50))
                 (create-fertilizer-product! "Phosphorus blend" "High-P" (hash n 50 p 200 k 50))
                 (create-fertilizer-product! "Potassium blend" "High-K" (hash n 50 p 50 k 200))

                 (define recipe (find-ferti-recipe))

                 (check-equal? (length recipe) 4 "Should have 4 fertilizer options")

                 ;; Verify solution is non-negative
                 (for ([pair recipe])
                   (check-true (>= (cdr pair) 0)
                               (format "~a quantity must be non-negative"
                                       (fertilizer-name (car pair)))))

                 (disconnect!)))))
Copyright 2019--2026 Marius PETER