forked from informedica/GenPRES
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoseRule.fs
More file actions
1274 lines (1124 loc) · 48.8 KB
/
DoseRule.fs
File metadata and controls
1274 lines (1124 loc) · 48.8 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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Informedica.GenForm.Lib
module DoseRule =
open System
open MathNet.Numerics
open FsToolkit.ErrorHandling.ResultCE
open FSharp.Data
open FSharp.Data.JsonExtensions
open Informedica.Utils.Lib
open Informedica.Utils.Lib.BCL
open Informedica.GenCore.Lib.Ranges
open Utils
open GenFormResult
module Print =
open Informedica.GenUnits.Lib
let printFreqs (r : DoseRule) =
r.Frequencies
|> Option.map (fun vu ->
vu
|> Utils.ValueUnit.toString 0
)
|> Option.defaultValue ""
let printInterval (dr: DoseRule) =
if dr.IntervalTime = MinMax.empty then ""
else
dr.IntervalTime
|> MinMax.toString
"min. interval "
"min. interval "
"max. interval "
"max. interval "
let printTime (dr: DoseRule) =
if dr.AdministrationTime = MinMax.empty then ""
else
dr.AdministrationTime
|> MinMax.toString
"min. "
"min. "
"max. "
"max. "
let printDuration (dr: DoseRule) =
if dr.Duration = MinMax.empty then ""
else
dr.Duration
|> MinMax.toString
"min. duur "
"min. duur "
"max. duur "
"max. duur "
let printDose wrap (dr : DoseRule) =
let substDls =
dr.ComponentLimits
|> Array.collect _.SubstanceLimits
let formDls =
dr.ComponentLimits
|> Array.choose _.Limit
let useSubstDl = substDls |> Array.length > 0
// only use form dose limits if there are no substance dose limits
if useSubstDl then substDls
else formDls
|> Array.map (fun dl ->
let perDose = "/dosis"
let emptyS = ""
let printMinMaxDose = DoseLimit.printMinMaxDose ""
[
$"%s{dl.Rate |> printMinMaxDose emptyS}"
$"%s{dl.RateAdjust |> printMinMaxDose emptyS}"
$"%s{dl.PerTimeAdjust |> printMinMaxDose emptyS}"
$"%s{dl.PerTime |> printMinMaxDose emptyS}"
$"%s{dl.QuantityAdjust |> printMinMaxDose perDose}"
$"%s{dl.Quantity |> printMinMaxDose perDose}"
]
|> List.map String.trim
|> List.filter (String.IsNullOrEmpty >> not)
|> String.concat ", "
|> fun s ->
$"%s{dl.DoseLimitTarget |> LimitTarget.toString} %s{wrap}%s{s}{wrap}"
)
// get all medications from Kinderformularium
let kinderFormUrl = "https://www.kinderformularium.nl/geneesmiddelen.json"
let farmocoTherapeutischKompas = "https://www.farmacotherapeutischkompas.nl/bladeren/preparaatteksten/n/GENERIEK#doseringen"
let private _medications () =
let replace =
[
"Ergocalciferol / fytomenadion / retinol / tocoferol (Vitamine A/D/E/K)",
"ergocalciferol-fytomenadion-retinol-tocoferol-vitamine-adek"
"Natriumdocusaat (al dan niet i.c.m. sorbitol)",
"natriumdocusaat-al-dan-niet-icm-sorbitol"
]
let res = JsonValue.Load kinderFormUrl
[ for v in res do
{|
id = v?id.AsString()
generic = v?generic_name.AsString().Trim().ToLower()
|}
]
|> List.distinct
let getKFMedications = Memoization.memoize _medications
let getLink source gen =
getKFMedications ()
|> List.tryFind (fun m ->
m.generic
|> String.split "+"
|> List.map String.trim
|> String.concat "/"
|> String.equalsCapInsens gen
)
|> Option.bind (fun m ->
let gen = gen |> String.replace "/" "-"
match source with
| _ when source = "NKF" ->
$"[Kinderformularium](https://www.kinderformularium.nl/geneesmiddel/{m.id}/{gen})"
|> Some
| _ when source = "FK" ->
$"[Farmacotherapeutisch Kompas](https://www.farmacotherapeutischkompas.nl/bladeren/preparaatteksten/n/{gen}#doseringen)"
|> Some
| _ -> None
)
/// See for use of anonymous record in
/// fold: https://github.com/dotnet/fsharp/issues/6699
let toMarkdown (rules : DoseRule array) =
let generic_md generic =
$"\n\n# %s{generic}\n\n---\n"
let route_md route products synonyms =
if synonyms |> String.isNullOrWhiteSpace then
$"\n\n### Route: %s{route}\n\n#### Producten\n%s{products}\n"
else
$"\n\n### Route: %s{route}\n\n#### Producten\n%s{products}\n\n#### Synoniemen\n%s{synonyms}\n"
let product_md product = $"* %s{product}"
let synonyms_md names =
if names |> Seq.isEmpty then ""
else
let names = names |> String.concat ", "
$"* %s{names}"
let indication_md indication = $"\n\n## Indicatie: %s{indication}\n\n---\n"
let doseCapt_md = "\n\n#### Doseringen\n\n"
let dose_md dt dose freqs intv time dur =
let dt = dt |> DoseType.toDescription
let freqs =
if freqs |> String.isNullOrWhiteSpace then ""
else
$" in %s{freqs}"
let s =
[
if intv |> String.isNullOrWhiteSpace |> not then
$" %s{intv}"
if time |> String.isNullOrWhiteSpace |> not then
$" inloop tijd %s{time}"
if dur |> String.isNullOrWhiteSpace |> not then
$" %s{dur}"
]
|> String.concat ", "
|> fun s ->
if s |> String.isNullOrWhiteSpace then ""
else
$" (%s{s |> String.trim})"
$"* *%s{dt}*: %s{dose}%s{freqs}%s{s}"
let patient_md patient =
let patient =
if patient |> String.notEmpty then patient
else "alle patienten"
$"\n\n##### Patient: **%s{patient}**\n\n"
let printDoses (rules : DoseRule array) =
("", rules |> Array.groupBy _.DoseType)
||> Array.fold (fun acc (dt, ds) ->
let pedForm =
let link =
ds
|> Array.tryHead
|> Option.bind (fun dr ->
dr.Generic |> getLink dr.Source
)
|> Option.defaultValue "*Lokaal*"
ds
|> Array.map _.ScheduleText
|> Array.distinct
|> function
| [| s |] -> $"\n\n%s{link}: %s{s}"
| _ -> ""
ds
|> Array.fold (fun acc r ->
let dose =
r
|> printDose ""
|> Array.distinct
|> String.concat ", "
let freqs = r |> printFreqs
let intv = r |> printInterval
let time = r |> printTime
let dur = r |> printDuration
let md = dose_md dt dose freqs intv time dur
if acc |> String.containsCapsInsens md then acc // prevent duplicate doserule per form print
else
$"%s{acc}\n%s{md}%s{pedForm}"
) acc
)
({| md = ""; rules = [||] |},
rules
|> Array.groupBy _.Generic
)
||> Array.fold (fun acc (generic, rs) ->
{| acc with
md = generic_md generic
rules = rs
|}
|> fun r ->
if r.rules = Array.empty then r
else
(r, r.rules |> Array.groupBy _.Indication)
||> Array.fold (fun acc (indication, rs) ->
{| acc with
md = acc.md + (indication_md indication)
rules = rs
|}
|> fun r ->
if r.rules = Array.empty then r
else
(r, r.rules |> Array.groupBy _.Route)
||> Array.fold (fun acc (route, rs) ->
let prods =
rs
|> Array.collect _.ComponentLimits
|> Array.collect _.Products
|> Array.sortBy (fun p ->
p.Substances
|> Array.sumBy (fun s ->
s.Concentration
|> Option.map ValueUnit.getValue
|> Option.bind Array.tryHead
|> Option.defaultValue 0N
)
)
|> Array.map (fun p ->
if p.GPK |> String.IsNullOrWhiteSpace then p.Label
else $"{p.GPK} - {p.Label}"
|> product_md
)
|> Array.distinct
|> String.concat "\n"
let synonyms =
rs
|> Array.collect _.ComponentLimits
|> Array.collect _.Products
|> Array.collect _.Synonyms
|> Array.distinct
|> synonyms_md
{| acc with
md = acc.md + (route_md route prods synonyms)
+ doseCapt_md
rules = rs
|}
|> fun r ->
if r.rules = Array.empty then r
else
(r, r.rules
|> Array.sortBy (fun d -> d.PatientCategory |> PatientCategory.sortBy)
|> Array.groupBy _.PatientCategory)
||> Array.fold (fun acc (pat, rs) ->
let doses =
rs
|> Array.sortBy (fun r -> r.DoseType |> DoseType.sortBy)
|> printDoses
let pat = pat |> PatientCategory.toString
{| acc with
rules = rs
md =
acc.md +
(patient_md pat) +
$"\n{doses}"
|}
)
)
)
)
|> _.md
let printGenerics generics (doseRules : DoseRule[]) =
doseRules
|> generics
|> Array.sort
|> Array.map(fun g ->
doseRules
|> Array.filter (fun dr -> dr.Generic = g)
|> toMarkdown
)
open Informedica.GenUnits.Lib
module GenPresProduct = Informedica.ZIndex.Lib.GenPresProduct
module GenericProduct = Informedica.ZIndex.Lib.GenericProduct
/// <summary>
/// Reconstitute the products in a DoseRule that require reconstitution.
/// </summary>
/// <param name="mapping"></param>
/// <param name="dep">The Department to select the reconstitution</param>
/// <param name="loc">The VenousAccess location to select the reconstitution</param>
/// <param name="dr">The DoseRule</param>
let reconstitute mapping loc dep (dr : DoseRule) =
let warns = ResizeArray<string>()
let reconstitute = Product.reconstitute mapping loc dep
let dr =
{ dr with
ComponentLimits =
dr.ComponentLimits
|> Array.map (fun dl ->
{ dl with
Products =
dl.Products
|> Array.collect (fun prod ->
let prods, newWarns = reconstitute dr.Route prod
warns.AddRange(newWarns)
prods
)
}
)
}
dr,
warns |> Seq.distinct
let fromTupleInclExcl = MinMax.fromTuple Inclusive Exclusive
let fromTupleInclIncl = MinMax.fromTuple Inclusive Inclusive
let mapToDoseRule (r : DoseRuleData) =
try
{
Source = r.Source
Indication = r.Indication
Generic = r.Generic
Form = r.Form
Brand =
if r.Brand |> String.isNullOrWhiteSpace then None
else r.Brand |> Some
Route = r.Route
ScheduleText = r.ScheduleText
PatientCategory =
{
Location = None
Department =
if r.Department |> String.isNullOrWhiteSpace then None
else
r.Department |> Some
Gender = r.Gender
Age =
(r.MinAge, r.MaxAge)
|> fromTupleInclExcl (Some Utils.Units.day)
Weight =
(r.MinWeight, r.MaxWeight)
|> fromTupleInclExcl (Some Utils.Units.weightGram)
BSA =
(r.MinBSA, r.MaxBSA)
|> fromTupleInclExcl (Some Utils.Units.bsaM2)
GestAge =
(r.MinGestAge, r.MaxGestAge)
|> fromTupleInclExcl (Some Utils.Units.day)
PMAge =
(r.MinPMAge, r.MaxPMAge)
|> fromTupleInclExcl (Some Utils.Units.day)
Access = AnyAccess
}
DoseType = r.DoseText |> DoseType.fromString r.DoseType
AdjustUnit = r.AdjustUnit |> Units.adjustUnit
Frequencies =
match r.FreqUnit |> Units.freqUnit with
| None -> None
| Some u ->
if r.Frequencies |> Array.isEmpty then None
else
r.Frequencies
|> ValueUnit.withUnit u
|> Some
AdministrationTime =
(r.MinTime, r.MaxTime)
|> fromTupleInclIncl (r.TimeUnit |> Utils.Units.timeUnit)
IntervalTime =
(r.MinInterval, r.MaxInterval)
|> fromTupleInclIncl (r.IntervalUnit |> Utils.Units.timeUnit)
Duration =
(r.MinDur, r.MaxDur)
|> fromTupleInclIncl (r.DurUnit |> Utils.Units.timeUnit)
FormLimit = None
ComponentLimits = [||]
RenalRule = None
}
|> Ok
with
| exn ->
("mapToDoseRule", Some exn) |> ErrorMsg |> Error
let getData dataUrlId : GenFormResult<_> =
try
Web.getDataFromSheet dataUrlId "DoseRules"
|> fun data ->
let getColumn =
data
|> Array.head
|> Csv.getStringColumn
data
|> Array.tail
|> Array.distinctBy (fun row -> row |> Array.tail)
|> Array.map (fun r ->
let get = getColumn r
let toBrOpt = BigRational.toBrs >> Array.tryHead
{
Source = get "Source"
Indication = get "Indication"
Generic = get "Generic"
Form = get "Form"
Brand = get "Brand"
GPKs =
get "GPKs"
|> String.splitAt ';'
|> Array.map String.trim
|> Array.filter String.notEmpty
|> Array.distinct
Route = get "Route"
Department = get "Dep"
ScheduleText =
try
get "ScheduleText"
with
| _ -> ""
Gender = get "Gender" |> Gender.fromString
MinAge = get "MinAge" |> toBrOpt
MaxAge = get "MaxAge" |> toBrOpt
MinWeight = get "MinWeight" |> toBrOpt
MaxWeight = get "MaxWeight" |> toBrOpt
MinBSA = get "MinBSA" |> toBrOpt
MaxBSA = get "MaxBSA" |> toBrOpt
MinGestAge = get "MinGestAge" |> toBrOpt
MaxGestAge = get "MaxGestAge" |> toBrOpt
MinPMAge = get "MinPMAge" |> toBrOpt
MaxPMAge = get "MaxPMAge" |> toBrOpt
DoseType = get "DoseType"
DoseText = get "DoseText"
Frequencies = get "Freqs" |> BigRational.toBrs
DoseUnit = get "DoseUnit"
AdjustUnit = get "AdjustUnit"
FreqUnit = get "FreqUnit"
RateUnit = get "RateUnit"
MinTime = get "MinTime" |> toBrOpt
MaxTime = get "MaxTime" |> toBrOpt
TimeUnit = get "TimeUnit"
MinInterval = get "MinInt" |> toBrOpt
MaxInterval = get "MaxInt" |> toBrOpt
IntervalUnit = get "IntUnit"
MinDur = get "MinDur" |> toBrOpt
MaxDur = get "MaxDur" |> toBrOpt
DurUnit = get "DurUnit"
Component = get "Component"
Substance = get "Substance"
MinQty = get "MinQty" |> toBrOpt
MaxQty = get "MaxQty" |> toBrOpt
MinQtyAdj = get "MinQtyAdj" |> toBrOpt
MaxQtyAdj = get "MaxQtyAdj" |> toBrOpt
MinPerTime = get "MinPerTime" |> toBrOpt
MaxPerTime = get "MaxPerTime" |> toBrOpt
MinPerTimeAdj = get "MinPerTimeAdj" |> toBrOpt
MaxPerTimeAdj = get "MaxPerTimeAdj" |> toBrOpt
MinRate = get "MinRate" |> toBrOpt
MaxRate = get "MaxRate" |> toBrOpt
MinRateAdj = get "MinRateAdj" |> toBrOpt
MaxRateAdj = get "MaxRateAdj" |> toBrOpt
Products = [||]
}
)
|> Array.distinct
|> createOkNoMsgs
with
| exn ->
createError "getDataResult" exn
let doseRuleDataIsValid (dd: DoseRuleData) =
match dd.DoseText |> DoseType.fromString dd.DoseType with
| NoDoseType ->
// assume an empty dose type is deliberate
if dd.DoseType |> String.notEmpty then
$"Not valid dose rule data:\n{dd}\n"
|> ConsoleWriter.NewLineNoTime.writeWarningMessage
false
| Once _ -> true
| OnceTimed _ ->
dd.MaxTime.IsSome && dd.TimeUnit |> String.notEmpty
| Discontinuous _ ->
dd.Frequencies |> Array.length > 0 && dd.FreqUnit |> String.notEmpty
| Timed _ ->
dd.Frequencies |> Array.length > 0 && dd.FreqUnit |> String.notEmpty &&
dd.MaxTime.IsSome && dd.TimeUnit |> String.notEmpty
| Continuous _ ->
dd.RateUnit |> String.notEmpty &&
(dd.MaxRate.IsSome || dd.MaxRateAdj.IsSome)
let processDoseRuleData prods routeMapping (data, msgs) : GenFormResult<_> =
let warnings = Collections.Generic.Dictionary<_, _>()
let grouped =
data
|> Array.filter doseRuleDataIsValid
|> Array.groupBy (fun d ->
match d.Form, d.Brand with
| s, _ when s |> String.notEmpty -> $"{d.Generic} ({d.Form |> String.toLower})"
| _, s when s |> String.notEmpty -> $"{d.Generic} ({d.Brand |> String.toLower |> String.capitalize})"
| _ -> d.Generic
,
d.Route
)
let procesGroup ((gen: string, rte: string), rs: DoseRuleData[]) =
async {
return
rs
|> Array.collect (fun r ->
let filtered =
if r.GPKs |> Array.isEmpty then
prods
|> Product.filter
routeMapping
{ Filter.doseFilter with
Generic = r.Component |> Some
Route = rte |> Some
}
else
prods
|> Array.filter (fun p -> r.GPKs |> Array.exists (String.equalsCapInsens p.GPK))
if filtered |> Array.length = 0 then
let key = $"{gen} {rte}"
if warnings.ContainsKey(key) |> not then
let msg =
$"{key}: no products found"
warnings.Add(key, msg)
[|
{ r with
Products =
[|
rs
|> Array.map _.Substance
|> Array.filter String.notEmpty
|> Array.distinct
|> Product.create gen rte
|]
}
|]
else
filtered
// create doserule per pharmaceutical form
|> Array.groupBy _.Form
|> Array.collect (fun (_, ps) ->
// make sure that all products have the same unit group
ps
|> Array.groupBy (_.FormUnit >> ValueUnit.Group.unitToGroup)
|> function
| [|_, ps|] ->
ps
|> Array.map (fun product ->
{ r with
Generic = gen
Form = product.Form |> String.toLower
Products =
if r.GPKs |> Array.length > 0 then ps
else
ps
|> Product.filter routeMapping
{ Filter.doseFilter with
Generic = r.Component |> Some
Form = product.Form |> Some
Route = rte |> Some
}
}
)
|> Array.distinct
| xs ->
xs
|> Array.collect (fun (_, ps) ->
ps
|> Array.map (fun product ->
let u =
product.FormUnit
|> Units.toString false Units.Dutch Units.Short
{ r with
Generic = gen
Form =
$"{product.Form |> String.toLower} ({u})"
Products =
if r.GPKs |> Array.length > 0 then ps
else
ps
|> Product.filter
routeMapping
{ Filter.doseFilter with
Generic = r.Component |> Some
Form = product.Form |> Some
Route = rte |> Some
}
}
)
|> Array.distinct
)
)
)
}
let chunkSize = Parallel.totalWorders
let data =
grouped
|> Array.chunkBySize chunkSize
|> Array.collect (Array.map procesGroup)
|> Async.Parallel
|> Async.RunSynchronously
|> Array.collect id
let msgs =
warnings.Values |> Seq.toList
|> List.map Warning
|> List.append msgs
(data, msgs)
|> Ok
let addFormLimits routeMapping formRoutes (dr : DoseRule) =
let prods =
dr.ComponentLimits
|> Array.collect _.Products
let droplets =
prods
|> Array.filter (fun p ->
p.Form |> String.containsCapsInsens "druppel"
)
|> Array.choose _.Divisible
|> Array.distinct
|> Array.tryExactlyOne
let setDroplet vu =
let v, u = vu |> ValueUnit.get
match droplets with
| None -> vu
| Some m ->
u
|> Units.Volume.dropletSetDropsPerMl m
|> ValueUnit.withValue v
if dr.Form |> String.isNullOrWhiteSpace then dr
else
prods
|> Array.map _.FormUnit
|> Array.tryExactlyOne
|> Option.defaultValue NoUnit
|> Mapping.filterFormRoutes routeMapping formRoutes dr.Route dr.Form
|> Array.map (fun rsu ->
{ DoseLimit.limit with
DoseLimitTarget = OrderableLimitTarget
Quantity =
{
Min = rsu.MinDoseQty |> Option.map Limit.Inclusive
Max = rsu.MaxDoseQty |> Option.map Limit.Inclusive
}
QuantityAdjust =
match dr.AdjustUnit with
| Some unt when unt |> Units.eqsUnit Units.Weight.kiloGram ->
{
Min = rsu.MinDoseQtyPerKg |> Option.map Limit.Inclusive
Max = rsu.MaxDoseQtyPerKg |> Option.map Limit.Inclusive
}
| _ -> DoseLimit.limit.QuantityAdjust
}
|> fun dl ->
if droplets |> Option.isNone then dl
else
{ dl with
DoseUnit =
droplets
|> Option.map Units.Volume.dropletWithDropsPerMl
|> Option.defaultValue rsu.DoseUnit
Quantity =
{
Min =
dl.Quantity.Min
|> Option.map (
Limit.apply
setDroplet
setDroplet
)
Max =
dl.Quantity.Max
|> Option.map (
Limit.apply
setDroplet
setDroplet
)
}
}
)
|> Array.distinct
|> Array.tryExactlyOne
|> function
| None -> dr
| Some formLimit ->
{ dr with FormLimit = Some formLimit }
let getDoseLimits (rs : DoseRuleData []) =
rs
|> Array.map (fun r ->
// the adjust unit
let adj = r.AdjustUnit |> Utils.Units.adjustUnit
// the dose unit
let du = r.DoseUnit |> Units.fromString
// the adjusted dose unit
let duAdj =
match adj, du with
| Some adj, Some du ->
du
|> Units.per adj
|> Some
| _ -> None
// the time unit
let tu = r.FreqUnit |> Utils.Units.timeUnit
// the dose unit per time unit
let duTime =
match du, tu with
| Some du, Some tu ->
du
|> Units.per tu
|> Some
| _ -> None
// the adjusted dose unit per time unit
let duAdjTime =
match duAdj, tu with
| Some duAdj, Some tu ->
duAdj
|> Units.per tu
|> Some
| _ -> None
// the rate unit
let ru = r.RateUnit |> Units.fromString
// the dose unit per rate unit
let duRate =
match du, ru with
| Some du, Some ru ->
du
|> Units.per ru
|> Some
| _ -> None
// the adjusted dose unit per rate unit
let duAdjRate =
match duAdj, ru with
| Some duAdj, Some ru ->
duAdj
|> Units.per ru
|> Some
| _ -> None
{
DoseLimitTarget =
if r.Substance |> String.isNullOrWhiteSpace then
r.Component |> ComponentLimitTarget
else
r.Substance |> SubstanceLimitTarget
AdjustUnit = adj
DoseUnit = du |> Option.defaultValue NoUnit
Quantity =
(r.MinQty, r.MaxQty)
|> fromTupleInclIncl du
QuantityAdjust =
(r.MinQtyAdj, r.MaxQtyAdj)
|> fromTupleInclIncl duAdj
PerTime =
(r.MinPerTime, r.MaxPerTime)
|> fromTupleInclIncl duTime
PerTimeAdjust =
(r.MinPerTimeAdj, r.MaxPerTimeAdj)
|> fromTupleInclIncl duAdjTime
Rate =
(r.MinRate, r.MaxRate)
|> fromTupleInclIncl duRate
RateAdjust =
(r.MinRateAdj, r.MaxRateAdj)
|> fromTupleInclIncl duAdjRate
}
)
let addDoseLimits routeMapping formRoutes (rs: DoseRuleData[]) (dr : DoseRule) =
{ dr with
ComponentLimits =
rs
|> Array.groupBy _.Component
|> Array.map (fun (cmp , rs) ->
let lim =
rs
// if no substance the dose limit is a component limit
|> Array.filter (_.Substance >> String.isNullOrWhiteSpace)
|> getDoseLimits
|> Array.tryExactlyOne
{
Name = cmp
GPKs = rs |> Array.collect _.GPKs
Limit = lim
Products =
rs
|> Array.collect _.Products
|> Array.filter (fun p ->
match lim with
| None -> true
| Some l ->
l.DoseUnit
|> ValueUnit.Group.eqsGroup Units.Count.times ||
l.DoseUnit
|> ValueUnit.Group.eqsGroup p.FormUnit
)
|> Array.distinct
SubstanceLimits =
rs
// if a substance the limit is a substance limit
|> Array.filter (_.Substance >> String.isNullOrWhiteSpace >> not)
|> getDoseLimits
}
)
}
|> addFormLimits routeMapping formRoutes
/// <summary>
/// Get the DoseRules from the Google Sheet.
/// </summary>
/// <remarks>
/// This function is memoized.
/// </remarks>
let get
dataUrl
routeMapping
formRoutes
prods
: GenFormResult<_>
=
let addDoseLimits = addDoseLimits routeMapping formRoutes
let map data =
result {
let! data, msgs =
fun () -> data |> processDoseRuleData prods routeMapping
|> StopWatch.clockFunc $"process data {data |> fst |> Array.length}"
// split in ok and error results
let rules, errs =
fun () ->
data
|> Array.map (fun d -> d, d |> mapToDoseRule)
|> Array.partition (snd >> Result.isOk)
|> StopWatch.clockFunc $"map to dose rules {data |> Array.length}"
// collect all messages
let msgs =
errs
|> Array.collect (fun (_, r) ->
match r with
| Ok _ -> [||]
| Error msg -> [| msg |]
)
|> Array.toList
|> List.append msgs
// process ok results
let rules =
fun () ->
(*
rules
|> Array.map (fun (d, r) ->
r |> Result.get, d
)
|> Array.groupBy fst
|> Array.map (fun (dr, rs) ->
dr |> addDoseLimits (rs |> Array.map snd)
)
*)
let chunkBySize = Parallel.totalWorders
let grouped =
rules
|> Array.map (fun (d, r) ->
r |> Result.get, d
)
|> Array.groupBy fst
grouped
|> Array.chunkBySize chunkBySize
|> Array.map (fun rs ->
async {
return
rs
|> Array.map (fun (dr, rs) ->
dr |> addDoseLimits (rs |> Array.map snd)
)
}
)
|> Async.Parallel
|> Async.RunSynchronously
|> Array.collect id
|> StopWatch.clockFunc $"add dose limits {rules |> Array.length}"
return! Ok (rules, msgs)
}
dataUrl
|> getData
|> Result.bind map
/// <summary>
/// Filter the DoseRules according to the Filter.
/// </summary>
/// <param name="routeMapping"></param>
/// <param name="filter">The Filter</param>
/// <param name="drs">The DoseRule array</param>
let filter routeMapping (filter : DoseFilter) (drs : DoseRule array) =
// if the filter is 'empty' just return all
if filter = Filter.doseFilter then drs
else
let eqs a b =
a
|> Option.map (String.equalsCapInsens b)
|> Option.defaultValue true
[|