-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3382 lines (2996 loc) · 149 KB
/
app.py
File metadata and controls
3382 lines (2996 loc) · 149 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
from shiny import App, ui, reactive, render
from pathlib import Path
import math
import pandas as pd
import os
import pickle
import numpy as np
import os
import pandas as pd
import scipy.stats
import re
import itertools
import string
import ast
import csv
#import matplotlib.pyplot as plt
summary_text = ""
# Define the UI
app_ui = ui.page_fluid(
ui.tags.title("PoolPy"),
ui.navset_tab(
ui.nav_panel("Pooling Methods Comparison",
# App logo/image at the top
ui.div(
ui.output_image("logo_img_main", height='0px'),
style="display: block; padding: 0; margin: 0; text-align: centre;"
),
# Centered Title
ui.h2("Pooling Methods Comparison", style="text-align: center; margin-top: 150px;"),
# Short description below the title
ui.div(
"This app evaluates the performances of different pooling methods. The corresponding designs can be downloaded below. ",
ui.br(),
"For details on the different methods and metrics and a user guide, see the ",
ui.a("Help", href="#help-section", id="nav-help-link", style="text-decoration: underline; cursor: pointer;"),
" section.",
ui.br(),
"To determine a max. number of positives based on prevalence, consult the ",
ui.a("Prevalence", href="#prevalence-section", id="nav-prevalence-link", style="text-decoration: underline; cursor: pointer;"),
" section.",
ui.br(),
"To decode results from a pooled experiment, consult the ",
ui.a("Decoder", href="#decoder-section", id="nav-decoder-link", style="text-decoration: underline; cursor: pointer;"),
" section.",
ui.br(),
"To generate a method file for a pipetting robot following a pooling design, consult the ",
ui.a("Automation", href="#automation-section", id="nav-automation-link", style="text-decoration: underline; cursor: pointer;"),
" section.",
ui.br(),
" For information on the code, visit our ",
ui.a("GitHub", href="https://github.com/trouillon-lab/PoolPy", style="text-decoration: underline;", target="_blank", rel="noopener noreferrer"),
".",
style="text-align: center; margin-bottom: 18px; font-size: 16px; color: #444;"
),
ui.tags.script('''
document.addEventListener('DOMContentLoaded', function() {
var helpLink = document.getElementById('nav-help-link');
if (helpLink) {
helpLink.addEventListener('click', function(event) {
event.preventDefault();
var tab = document.querySelector("[data-value='Help']");
if (tab) tab.click();
});
}
var prevalenceLink = document.getElementById('nav-prevalence-link');
if (prevalenceLink) {
prevalenceLink.addEventListener('click', function(event) {
event.preventDefault();
var tab = document.querySelector("[data-value='Prevalence']");
if (tab) tab.click();
});
}
var decoderLink = document.getElementById('nav-decoder-link');
if (decoderLink) {
decoderLink.addEventListener('click', function(event) {
event.preventDefault();
var tab = document.querySelector("[data-value='Decoder']");
if (tab) tab.click();
});
}
var automationLink = document.getElementById('nav-automation-link');
if (automationLink) {
automationLink.addEventListener('click', function(event) {
event.preventDefault();
var tab = document.querySelector("[data-value='Automation']");
if (tab) tab.click();
});
}
});
'''),
# Row with two input fields side by side (one on the left, one on the right)
ui.row(
ui.column(4),
ui.column(2, ui.input_numeric("n_samp", "Number of Samples:", value=20)),
ui.column(1),
ui.column(2, ui.input_numeric("differentiate", "Max. number of positives:", value=1)),
ui.column(2),
),
# ...existing code for Main page...
ui.row(
ui.column(
12,
ui.input_action_button("submit", "Enter", style="display: block; margin-left: auto; margin-right: auto;")
)
),
ui.hr(),
ui.div(
ui.h4("Last submitted values:"),
ui.output_ui("last_val"),
style="text-align: center;"
),
ui.hr(),
ui.div(
ui.h4("Database reply:"),
ui.output_ui("database_r"),
style="text-align: center;"
),
ui.hr(),
ui.panel_conditional(
"output.allow_downloads == 'true'",
ui.div(
ui.div(
ui.output_ui("summary_table_title"),
style="margin: 32px 0 32px 0;"
),
ui.div(
ui.output_ui("summary_colored_table"),
style="display: flex; justify-content: center;"
),
# Add a new output to render the colored summary table in the server function, not in the UI definition
ui.div(
ui.output_ui("summary_text"),
style="margin: 18px 0 0 0; color: #555; font-size: 15px; text-align: center;"
),
ui.div(
ui.download_button("download_summary", "Download summary"),
style="text-align: center; margin-top: 20px;"
),
ui.div("", style="margin-top: -32px;")
)
),
ui.panel_conditional(
"output.allow_fly_table == 'true'",
ui.div(
ui.output_ui("fly_summary_table_title"),
ui.output_ui("fly_summary_colored_table"),
style="display: flex; justify-content: center; flex-direction: column; margin-bottom: 20px;"
),
),
ui.div("", style="height: 52px;"),
ui.div(
ui.h4("Downloads & code"),
style="text-align: center;"
),
ui.div("", style="height: 12px;"),
ui.panel_conditional(
"output.allow_fly == 'true'",
ui.div(
ui.output_ui("fly_download_dip_title"),
ui.download_button("download_table_STD_fly", "STD"),
ui.download_button("download_table_CT_fly", "Chinese Remainder"),
ui.download_button("download_table_CT_bktrk_fly", "Ch. Rm. Backtrack"),
ui.download_button("download_table_CT_special_fly", "Ch. Rm. Special"),
style="text-align: center;",
),
ui.div("", style="height: 20px;")
),
ui.div("", style="height: 12px;"),
ui.panel_conditional(
"output.allow_fly == 'true'",
ui.div(
ui.output_ui("fly_download_ind_title"),
ui.download_button("download_table_matrix_fly", "Matrix"),
ui.download_button("download_table_2d_fly", "2-dim"),
ui.download_button("download_table_3d_fly", "3-dim"),
ui.download_button("download_table_4d_fly", "4-dim"),
ui.download_button("download_table_binary_fly", "Binary"),
style="text-align: center;",
),
ui.div("", style="height: 32px;")
),
ui.div(
ui.h4("Precomputed pooling designs"),
style="text-align: center;"
),
ui.div(
"All precomputed pooling designs are available on Zenodo.",
ui.br(),
"Access the repository at: ",
ui.a("DOI: 10.5281/zenodo.18660061", href="https://doi.org/10.5281/zenodo.18660061", style="text-decoration: underline;", target="_blank", rel="noopener noreferrer"),
style="color: #555; font-size: 18px; text-align: center;"
),
ui.div("", style="height: 32px;"),
ui.panel_conditional(
"output.allow_downloads == 'lala'", # change lala with true to make available
ui.div(
ui.h4("Downloadable precomputed random design", style="margin-bottom: 20px;"),
#ui.download_button("download_table_matrix", "Matrix"),
#ui.download_button("download_table_2d", "2-dim"),
#ui.download_button("download_table_3d", "3-dim"),
#ui.download_button("download_table_4d", "4-dim"),
ui.download_button("download_table_random", "Random"),
#ui.download_button("download_table_STD", "STD"),
#ui.download_button("download_table_CT", "Chinese remainder"),
#ui.download_button("download_table_CTB", "Chinese rm bktrk"),
#ui.download_button("download_table_CTS", "Chinese rm special"),
#ui.download_button("download_table_binary", "Binary"),
style="text-align: center;",
),
ui.div("", style="height: 20px;"),
),
ui.div(
ui.h4("Command to generate designs locally"),
ui.output_ui("commands"),
style="text-align: center;"
),
ui.panel_conditional(
"output.allow_fly == 'true'",
ui.div(
ui.h4("Command to decode results locally"),
ui.output_ui("decode"),
style="text-align: center;"
),
),
ui.div(
ui.output_text_verbatim("allow_downloads"),
style="position: fixed; bottom: 2px; right: 2px; opacity: 0.05; font-size: 8px; z-index: 1; pointer-events: none;"
),
ui.div(
ui.output_text_verbatim("allow_fly"),
style="position: fixed; bottom: 2px; right: 2px; opacity: 0.05; font-size: 8px; z-index: 1; pointer-events: none;"
),
ui.div(
ui.output_text_verbatim("allow_fly_table"),
style="position: fixed; bottom: 2px; right: 2px; opacity: 0.05; font-size: 8px; z-index: 1; pointer-events: none;"
),
ui.div("", style="height: 80px;"),
ui.tags.script("""
function copyCommand(command) {
navigator.clipboard.writeText(command).then(function() {
alert('Copied to clipboard: ' + command);
}).catch(function(error) {
console.error('Failed to copy text: ', error);
});
}
"""),
ui.tags.script('''
document.getElementById('n_samp').addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
document.getElementById('submit').click();
}
});
document.getElementById('differentiate').addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
document.getElementById('submit').click();
}
});
''')
),
ui.nav_panel("Decoder",
ui.div(
ui.output_image("logo_img_decoder", height='0px'),
style="display: block; padding: 0; margin: 0; text-align: centre;"
),
ui.h2("Decoder", style="text-align: center; margin-top: 150px;"),
# Short description below the title
ui.div(
"Results from tests done following a pooling design from PoolPy can be decoded here.",
ui.br(),
"First, load your design file (only csv designs files generated by PoolPy are accepted).",
ui.br(),
"Then, enter your readout showing which pools were positive. Single-readout mode: type readout as a list of positive pools (e.g. 1,3,5).",
ui.br(),
"Multi-readout mode: upload a csv file which contain the list of positive pools (e.g. 1,3,5) for each readout as a different row.",
style="text-align: center; margin-bottom: 18px; font-size: 16px; color: #444;"
),
ui.div(
ui.input_file("uploaded_csv_decoder", "Upload your csv design file ", accept=[".csv"], multiple=False),
style="display: flex; justify-content: center; margin-bottom: 22px;"
),
ui.div(
ui.input_text(
"readout_string",
"Single readout (positive pools):",
value="",
placeholder="Enter comma-separated values"
),
ui.input_action_button("submit_text_readout", "Send", style="margin-left: 10px;"),
style="display: flex; justify-content: center; align-items: center; margin-bottom: 18px; gap: 10px;"
),
ui.div(
ui.tags.div(
"OR",
style="text-align: center; font-weight: bold; margin-bottom: 12px; font-size: 16px; color: #666;"
),
ui.div(
ui.input_file("uploaded_csv_readout", "Multi readout: upload as CSV file", accept=[".csv"], multiple=False),
ui.input_action_button("submit_csv_readout", "Send", style="margin-left: 10px;"),
style="display: flex; justify-content: center; align-items: center; gap: 10px;"
),
style="display: flex; flex-direction: column; align-items: center; margin-bottom: 18px;"
),
ui.div(
ui.input_text(
"decoder_diff",
"Max. number of positives (optional):",
placeholder="Leave empty for auto inference"
),
style="display: flex; justify-content: center; margin-bottom: 32px;"
),
ui.tags.script('''
document.addEventListener('DOMContentLoaded', function() {
["readout_string", "decoder_diff"].forEach(function(id) {
var el = document.getElementById(id);
if (el) {
el.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
var btn = document.getElementById('submit_text_readout');
if (btn) btn.click();
}
});
}
});
});
'''),
ui.div(
ui.output_ui("database_r_decoder"),
style="text-align: center; margin-bottom: 18px; font-size: 16px; color: #444;"
),
ui.panel_conditional(
"output.allow_decoder == 'true' && output.decoder_is_csv == 'true'",
ui.div(
ui.download_button("download_decoder_csv", "Download decoded CSV"),
ui.download_button("download_sample_probabilities", "Download sample probabilities"),
style="display: flex; justify-content: center; gap: 32px; margin-bottom: 32px;"
),
),
ui.panel_conditional(
"output.allow_decoder == 'true' && output.decoder_is_text == 'true'",
ui.div(
ui.download_button("download_decoder_output", "Download decoder output"),
style="display: flex; justify-content: center; gap: 32px; margin-bottom: 32px;"
),
),
ui.div(
ui.output_text_verbatim("allow_decoder"),
style="position: fixed; bottom: 2px; right: 2px; opacity: 0.05; font-size: 8px; z-index: 1; pointer-events: none;"
),
ui.div(
ui.output_text_verbatim("decoder_is_text"),
style="position: fixed; bottom: 2px; right: 2px; opacity: 0.05; font-size: 8px; z-index: 1; pointer-events: none;"
),
ui.div(
ui.output_text_verbatim("decoder_is_csv"),
style="position: fixed; bottom: 2px; right: 2px; opacity: 0.05; font-size: 8px; z-index: 1; pointer-events: none;"
),
),
ui.nav_panel("Prevalence",
ui.div(
ui.output_image("logo_img_prev", height='0px'),
style="display: block; padding: 0; margin: 0; text-align: centre;"
),
ui.h2("Prevalence", style="text-align: center; margin-top: 150px;"),
ui.div(
ui.div(
"This section is meant to guide the decision of pooling parameters for specific use cases. Particularly, this is to choose a max. number of positive samples and a number of test batches.",
ui.br(),
"Based on a provided prevalence estimate, error rates are reported over ranges of sample (and batch) numbers (S; rows) and of max. number of positive samples (D; columns).",
ui.br(),
"The tables show the probability of making at least one mistake while reading the results of either one (left) or multiple combined (right) combinatorial pooling batch(es).",
style="text-align: center; color: #444; font-size: 16px;"
),
style="text-align: center; margin-bottom: 18px;"
),
ui.div(
ui.row(
ui.column(2),
ui.column(3,
ui.input_numeric("prev_n_samp", "Number of Samples:", value=100),
),
ui.column(3,
ui.div(
ui.input_numeric(
"prev_prevalence",
"Prevalence (as fraction):",
value=0.01,
),
style="min-width: 220px; max-width: 100%; width: 100%; display: flex; align-items: center;"
)
),
ui.column(3,
ui.input_numeric("prev_max_error", "Maximum acceptable error:", value=0.05),
),
),
style="margin-top: 30px;"
),
ui.div(
ui.input_action_button("prev_submit", "Enter", style="display: block; margin: 20px auto 0 auto;"),
style="text-align: center;"
),
ui.tags.script('''
document.addEventListener('DOMContentLoaded', function() {
["prev_n_samp", "prev_prevalence", "prev_max_error"].forEach(function(id) {
var el = document.getElementById(id);
if (el) {
el.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
var btn = document.getElementById('prev_submit');
if (btn) btn.click();
}
});
}
});
});
'''),
ui.hr(),
ui.div(
ui.h4("Last submitted values:"),
ui.output_ui("last_val_prev"),
style="text-align: center;"
),
ui.div(
ui.output_ui("prevalence_error_table"),
style="margin-top: 30px; display: flex; justify-content: center;"
),
ui.div(
ui.output_ui("prevalence_legend"),
style="margin-top: 18px; display: flex; justify-content: center;"
),
#redundant?
# ui.div(
# ui.output_ui("prevalence_explanation"),
# style="margin-top: 8px; display: flex; justify-content: center;"
# ),
),
ui.nav_panel("Automation",
ui.div(
ui.output_image("logo_img_automation", height='0px'),
style="display: block; padding: 0; margin: 0; text-align: centre;"
),
ui.h2("Automation", style="text-align: center; margin-top: 150px;"),
# Short description below the title
ui.div(
"This tool generates a method file for a pipetting robot to follow a pooling design file.",
ui.br(),
"Load your design file below (only csv designs files generated by PoolPy are accepted).",
ui.br(),
"The generated file lists all pipetting steps required to generate the pools following the vendor's format. If your brand is not supported, reach out to us.",
ui.br(),
"Volumes and plate names might have to be adjusted to your specific use case.",
style="text-align: center; margin-bottom: 18px; font-size: 16px; color: #444;"
),
ui.div(
ui.input_file("uploaded_csv_auto", "Upload your csv design file", accept=[".csv"], multiple=False),
style="display: flex; justify-content: center; margin-bottom: 32px;"
),
ui.div(
ui.output_ui("database_r_auto"),
style="text-align: center; margin-bottom: 18px; font-size: 16px; color: #444;"
),
ui.panel_conditional(
"output.allow_robot == 'true'",
ui.div(
ui.download_button("download_biomek", "Download Biomek robot code"),
ui.download_button("download_hamilton", "Download Hamilton robot code"),
ui.download_button("download_opentron", "Download Opentron robot code"),
style="display: flex; justify-content: center; gap: 32px; margin-bottom: 32px;"
),
),
ui.div(
ui.output_text_verbatim("allow_robot"),
style="position: fixed; bottom: 2px; right: 2px; opacity: 0.05; font-size: 8px; z-index: 1; pointer-events: none;"
),
),
ui.nav_panel("Help",
ui.div(
ui.output_image("logo_img_methods", height='0px'),
style="display: block; padding: 0; margin: 0; text-align: cenrte;"
),
ui.h2("User guide", style="text-align: center; margin-top: 150px;"),
ui.div(
ui.download_button("download_pooled_pooling", "Download user guide"),
style="text-align: center; margin-top: 10px;"
),
ui.h2("Pooling methods", style="text-align: center; margin-top: 15px; margin-bottom: 10px;"),
ui.div(
ui.h4("Differentiate-dependent Pooling Methods:"),
ui.div(
"These methods change their design also based on the number of expected positive samples. They often are non-adaptive strategy and are well suited for high differentiate values.",
style="margin-bottom: 10px; font-size: 15px; color: #444;"
),
ui.tags.ul(
ui.tags.li(ui.tags.b("Random"), ": Semi-adaptive method where pools are formed by randomly assigning samples."),
ui.tags.li(ui.tags.b("STD"), ": Non-adaptive method based on prime numbers and modulus operations."),
ui.tags.li(ui.tags.b("Chinese Remainder methods"), ": Non-adaptive method based on the Chinese Remainder Theorem, with variants for backtracking (backtrack) and special cases (special)."),
ui.tags.li(ui.tags.b("Hierachical"), ": Strictly adaptive method that iteratively partitions the set of possible positive samples. " \
"For this method, the N pools metric lists the number of splits at each stage. " \
"For example, [3,3] means first divide samples into 3 pools (as equal as possible), then test and split any positive pool into 3 again. " \
"After testing of these pools, each sample from each positive pool finally needs to be individually tested." \
),
),
ui.h4("Differentiate-independent Pooling Methods:"),
ui.div(
"These methods do not change their output design based on the number of expected positive samples. They are to be used with caution if more than 1 positive sample is expected.",
style="margin-bottom: 10px; font-size: 15px; color: #444;"
),
ui.tags.ul(
ui.tags.li(ui.tags.b("Matrix"), ": Semi-adaptive method where each sample is included in a unique row and column pool."),
ui.tags.li(ui.tags.b("Multidimensional (3D, 4D, ...)"), ": Semi-adaptive method where samples are arranged in higher-dimensional matrices, each coordinate in each dimension representing a pool."),
ui.tags.li(ui.tags.b("Binary"), ": Semi-adaptive method where samples are assigned to pools according to a binary code, maximizing information per test."),
),
ui.h4("Metrics in the Summary Table:"),
ui.tags.ul(
ui.tags.li(ui.tags.b("Method"), ": Name of the pooling method used."),
ui.tags.li(ui.tags.b("Mean experiments"), ": Average number of tests required to identify the positive samples."),
ui.tags.li(ui.tags.b("Max. samples per pool"), ": Maximum number of samples combined in any single pool."),
ui.tags.li(ui.tags.b("N pools"), ": Total number of pools used in the first step of the strategy. For Hierachical this is a list of splits, explained above."),
ui.tags.li(ui.tags.b("Percentage check"), ": Fraction of cases requiring additional verification or retesting beyond the first step."),
ui.tags.li(ui.tags.b("Mean extra experiments"), ": Average number of extra tests needed beyond the first step."),
ui.tags.li(ui.tags.b("Max experiments per sample"), ": Maximum number of times an individual sample is tested."),
),
ui.h4("Decoder types:"),
ui.div(
"The decoder auto infers the type of readout and returns a 'type' alongside the positive samples. This characterisitc has four possible distinct values",
style="margin-bottom: 10px; font-size: 15px; color: #444;"
),
ui.tags.ul(
ui.tags.li(ui.tags.b("Continuous"), ": Used if the readout is inferred to be continuous and the single well value is inferred via penalized regression."),
ui.tags.li(ui.tags.b("Unique"), ": Used if the readout is binary and there exists only one set of positive samples (of maximum 'differentiate' samples) that can provide the measured readout"),
ui.tags.li(ui.tags.b("Multiple"), ": Used if the readout is binary and there exists multiple sets of positive samples (of maximum 'differentiate' samples) that can provide the measured readout"),
ui.tags.li(ui.tags.b("Putative"), ": Used if the readout is binary and there exists more sets of positive samples (of maximum 'differentiate' samples) that can provide the measured readout than the number of unique samples across all sets."),
),
ui.h4("Notation:"),
ui.tags.ul(
ui.tags.li(ui.tags.b("D"), ": Differentiate, maximum number of positive samples."),
ui.tags.li(ui.tags.b("S"), ": Number of samples to test."),
ui.tags.li(ui.tags.b("ρ"), ": Prevalence of positives in the population."),
ui.tags.li(ui.tags.b("W"), ": Total number of pools needed for a method."),
),
style="max-width: 700px; margin: 0 auto; font-size: 16px; color: #333;"
)
),
)
)
WA_SUB_DIRECTORY='precomputed'
#SCRAMBLER_DIRECTORY='.\output'
MAX_DIFFERENTIATE=10
MAX_N=1000
MAX_PROD=2500
MAX_PREVALENCE=0.1
COLUMN_WIDTH=210
def process_metrics_data(metrics_data):
"""Process metrics dataframe: drop first column, rename, reorder, and sort."""
try:
# Only drop first column if it's unnamed (from CSV index)
if metrics_data.columns[0].startswith('Unnamed'):
metrics_data.drop(metrics_data.columns[0], axis=1, inplace=True)
dict_ren={'N wells':'N pools (W)', 'Max compunds per well': 'Max compounds in a pool'}
metrics_data.rename(columns=dict_ren, inplace=True)
# Rename pooling strategies for consistency
if 'Pooling strategy' in metrics_data.columns:
metrics_data['Pooling strategy'] = metrics_data['Pooling strategy'].replace({
'Chinese special': 'Ch. Rm. special',
'Ch. rm. bktrk': 'Ch. Rm. backtrack'
})
if 'Max experiments per sample' in metrics_data.columns:
metrics_data = metrics_data[['Pooling strategy', 'Mean experiments', 'Mean steps', 'N pools', 'Max samples per pool', 'Percentage check', 'Mean extra experiments', 'Max experiments per sample']]
else:
metrics_data = metrics_data[['Pooling strategy', 'Mean experiments', 'Mean steps', 'N pools', 'Max samples per pool', 'Percentage check', 'Mean extra experiments']]
metrics_data = metrics_data.sort_values(by='Mean experiments', ascending=True)
return metrics_data
except Exception as e:
print(f"Error processing metrics data: {e}")
return metrics_data
def from_id_to_well(id, offset=0):
plate=id//96
id=id-plate*96
row=id//12
column=id-row*12
well=chr(65 + row)
return str(plate+1+offset), str(well)+str(column+1)
def validate_WA_df(df):
"""
Check columns are 'Pool n' and index labels are 'Sample n' (n integer).
Also check that all values are binary (0 or 1).
Returns (True, success_message) or (False, error_message).
"""
if df is None or df.empty:
ret_text = "<span style='color: #c00; font-weight: bold;'>DataFrame is empty</span>"
return False, ret_text
col_pat = re.compile(r"^Pool (\d+)$")
idx_pat = re.compile(r"^Sample (\d+)$")
# validate columns
for c in df.columns:
if not col_pat.match(str(c)):
ret_text = f"<span style='color: #c00; font-weight: bold;'>Column name '{c}' does not match 'Pool n' format</span>"
return False, ret_text
# validate index
for i in df.index:
if not idx_pat.match(str(i)):
ret_text = f"<span style='color: #c00; font-weight: bold;'>Index label '{i}' does not match 'Sample n' format</span>"
return False, ret_text
# validate binary data
if not df.isin([0, 1]).all().all():
ret_text = "<span style='color: #c00; font-weight: bold;'>File contains non-binary values. All values must be 0 or 1.</span>"
return False, ret_text
# Success message in green
ret_text = "<span style='color: #2ecc40; font-weight: bold;'>File is correctly formatted.</span>"
return True, ret_text
def clean_WA(b):
b1=b.astype(int)
tmp1=pd.DataFrame(b1, columns=['Pool '+ str(i) for i in range(b1.shape[1])], index=['Sample '+ str(i) for i in range(b1.shape[0])])
return tmp1
def int_to_base(n, N):
""" Return base N representation for int n. """
base_n_digits = string.digits + string.ascii_lowercase + string.ascii_uppercase
result = ""
if n < 0:
sign = "-"
n = -n
else:
sign = ""
while n > 0:
q, r = divmod(n, N)
result += base_n_digits[r]
n = q
if result == "":
result = "0"
return sign + "".join(reversed(result))
def set_compund_list(a):
b=[]
for aa in a:
add=True
for bb in b:
if set(aa)==set(bb):
add=False
continue
if add:
b.append(aa)
return(b)
#Coumpound counter starts from 1
# Helper function for binary translation
def IntegerToBinaryTF(num: int, ls_bn: list)-> list:
if num >= 2:
ls_bn=IntegerToBinaryTF(num // 2, ls_bn)
ls_bn.append(num % 2==1)
return(ls_bn)
def split(a, n):
k, m = divmod(len(a), n)
return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))
def isprime(n:int):
return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None
def get_Gamma(q,N):
return(int(np.ceil(np.log(N)/np.log(q))-1))
def get_s(N,j,q):
vec=np.arange(N)
out_vec=vec.copy()
Gamma=get_Gamma(q,N)
for ct in range(Gamma):
c=ct+1
out_vec=out_vec+j**c*(vec//q**c)
return(out_vec)
def STD(N,q,k):
L=np.zeros((k,q,N))==1
for j in range(k):
s=get_s(N,j,q)
s=s%q
idc=np.arange(N)
L[j,s,idc]=True
L=L.reshape(-1,N)
return(L.T)
# Function to assign each compound to its wells
def well_selecter(compound: int, n_wells:int, differentiate=1) -> np.array:
if differentiate not in [1,2]:
print('For the moment this code is only able to create well assignments matrices to distinguish up to combinations of 2 active compounds')
return(-1)
if differentiate==1:
ls_bn=[]
used_wells=IntegerToBinaryTF(compound, ls_bn)
sel_wells=[False]*(n_wells-len(used_wells))+used_wells
if differentiate==2:
for i in range((n_wells-1)//3+1):
if 0<compound and compound <= n_wells-1-3*i:
sel_wells=(n_wells-1-3*i-compound)*[False]+[True]+i*3*[False]+[True]+[False]*(compound-1)
break
compound=compound-(n_wells-1-3*i)
return(np.array(sel_wells))
def assign_wells_mat(n_compounds:int, **kwargs)->np.array:
L1=np.ceil(np.sqrt(n_compounds))
L2=L1-1 if L1*(L1-1)>=n_compounds else L1
well_assigner=np.zeros((n_compounds, int(L1+L2)))==1
for i in range(n_compounds):
cp_id=[int(i//L2), int(L1+(i % L2))]
well_assigner[i,cp_id]=True
return(well_assigner)
# This functions also identifies the minimum number of wells needed for the compounds and level of detail (differentiate) selected
def assign_wells_bin(n_compounds:int, differentiate=1, **kwargs) -> np.array:
n_wells=int(np.ceil(np.log2(n_compounds +1)))
well_assigner=np.zeros((n_compounds, n_wells))==1
for i in range(n_compounds):
well_assigner[i,:]=well_selecter(i+1, n_wells, differentiate=1)
return(well_assigner)
''' Method 3: Pooling using multidimensional matrix design'''
def assign_wells_multidim(n_compounds:int, n_dims:int, **kwargs)->np.array:
L1=np.ceil(np.power(n_compounds, 1/n_dims))
i=0
while np.power(L1, n_dims-i-1)*np.power(L1-1, i+1)>=n_compounds:
i=i+1
ls_dim=[L1]*(n_dims-i)+[L1-1]*i
up_samps=np.prod(np.array(ls_dim))
well_assigner=np.zeros((n_compounds, int(L1*(n_dims-i)+(L1-1)*i)))==1
for j in range(n_compounds):
cp_id=[]
jj=np.copy(j)
rem_dim=up_samps
past_dims=0
for k in range(n_dims):
rem_dim=rem_dim/ls_dim[k]
js=jj//rem_dim
jj=jj-js*rem_dim
jd=js+past_dims
cp_id.append(int(jd))
past_dims=past_dims+ls_dim[k]
well_assigner[j,cp_id]=True
return(well_assigner)
def get_params_multidims(n_compounds:int, n_dims:int, **kwargs):
L1=np.ceil(np.power(n_compounds, 1/n_dims))
i=0
while np.power(L1, n_dims-i-1)*np.power(L1-1, i+1)>=n_compounds:
i=i+1
ls_dim=[L1]*(n_dims-i)+[L1-1]*i
return(ls_dim)
def assign_wells_STD(n_compounds:int, differentiate=1, False_results=0, force_q=False, **kwargs):
N=n_compounds
t=differentiate
E=False_results
poss_q=[x for x in range(n_compounds) if isprime(x)]
for q in poss_q:
if t*get_Gamma(q,N)+2*E<q:
break
if isprime(force_q):
if t*get_Gamma(force_q,N)+2*E<force_q:
q=force_q
Gamma=get_Gamma(q,N)
k=t*Gamma+2*E+1
WA=STD(N,q,k)
return(WA)
def get_STD_params(n_compounds:int, differentiate=1, False_results=0, force_q=False, **kwargs):
N=n_compounds
t=differentiate
E=False_results
poss_q=[x for x in range(n_compounds) if isprime(x)]
for q in poss_q:
if t*get_Gamma(q,N)+2*E<q:
break
if isprime(force_q):
if t*get_Gamma(force_q,N)+2*E<force_q:
q=force_q
Gamma=get_Gamma(q,N)
k=t*Gamma+2*E+1
return(q,k)
def get_chinese_prameters(n_compounds:int, differentiate:int, backtrack=False, special_diff=False, **kwargs)->np.array:
prod=1
n=1
primes=[]
c_id=np.arange(n_compounds)
while prod<n_compounds**differentiate:
n=n+1
if isprime(n):
prod=prod*n
primes.append(n)
if backtrack:
T=np.inf
nprimes=np.array(primes)
ND=n_compounds**differentiate
ls_of_ls=[]
LMP=np.log(primes[-1])
for pi in primes:
LE=np.floor(LMP/np.log(pi)).astype(int)
ls_of_ls.append(list(range(LE+1)))
ls_iter=list(itertools.product(*ls_of_ls))
for id_combo, combo in enumerate(ls_iter):
carr=np.array(combo)
flt=carr>0
this_primes=nprimes[flt]
this_exp=carr[flt]
npc=this_primes**this_exp
if np.prod(npc)>=ND and np.sum(npc)<T:
T=np.sum(npc)
best_id=id_combo
combo=ls_iter[best_id]
carr=np.array(combo)
flt=carr>0
this_primes=nprimes[flt]
this_exp=carr[flt]
npc=this_primes**this_exp
return npc
if special_diff and differentiate==2:
q=np.ceil(np.log(n_compounds)/np.log(3)).astype(int)
t=int((q+5)*q/2)
return q,t
if special_diff and differentiate==3:
q=np.ceil(np.log(n_compounds)/np.log(2)).astype(int)
t=int((q-1)*q*2)
return q,t
return primes
def assign_wells_chinese_old(n_compounds:int, differentiate:int,**kwargs)->np.array:
prod=1
n=1
primes=[]
c_id=np.arange(n_compounds)
while prod<n_compounds**differentiate:
n=n+1
if isprime(n):
prod=prod*n
primes.append(n)
WA=np.zeros((np.sum(primes), n_compounds))==1
past_primes=0
for prime in primes:
temp_wa=np.zeros((prime, n_compounds))==1
for x in range(prime):
ids=c_id%prime==x
temp_wa[x, ids]=True
WA[past_primes:past_primes+prime,:]=temp_wa
past_primes=past_primes+prime
return(WA.T)
def assign_wells_chinese(n_compounds:int, differentiate:int, backtrack=False, special_diff=False, **kwargs)->np.array:
prod=1
n=1
primes=[]
c_id=np.arange(n_compounds)
while prod<n_compounds**differentiate:
n=n+1
if isprime(n):
prod=prod*n
primes.append(n)
if backtrack:
T=np.inf
nprimes=np.array(primes)
ND=n_compounds**differentiate
ls_of_ls=[]
LMP=np.log(primes[-1])
for pi in primes:
LE=np.floor(LMP/np.log(pi)).astype(int)
ls_of_ls.append(list(range(LE+1)))
ls_iter=list(itertools.product(*ls_of_ls))
for id_combo, combo in enumerate(ls_iter):
carr=np.array(combo)
flt=carr>0
this_primes=nprimes[flt]
this_exp=carr[flt]
npc=this_primes**this_exp
if np.prod(npc)>=ND and np.sum(npc)<T:
T=np.sum(npc)
best_id=id_combo
combo=ls_iter[best_id]
carr=np.array(combo)
flt=carr>0
this_primes=nprimes[flt]
this_exp=carr[flt]
npc=this_primes**this_exp
WA=np.zeros((np.sum(npc), n_compounds))==1
past_primes=0
for prime in npc:
temp_wa=np.zeros((prime, n_compounds))==1
for x in range(prime):
ids=c_id%prime==x
temp_wa[x, ids]=True
WA[past_primes:past_primes+prime,:]=temp_wa
past_primes=past_primes+prime
return(WA.T)
if special_diff and differentiate==2:
q=np.ceil(np.log(n_compounds)/np.log(3)).astype(int)
t=int((q+5)*q/2)
WA=np.zeros((t, n_compounds))==1
ls_nc3=[list(i)[::-1] for i in [int_to_base(j,3).zfill(q) for j in range(n_compounds)]]
for i in range(q):
for ii in range(3):
for j in range(n_compounds):
WA[3*i+ii,j]=True if int(ls_nc3[j][i])==int(ii) else False
k=3*q
for i in range(q):
for ii in range(i+1,q):
for j in range(n_compounds):
WA[k,j]=True if int(ls_nc3[j][i])==int(ls_nc3[j][ii]) else False
k+=1
return q,t
if special_diff and differentiate==3:
q=np.ceil(np.log(n_compounds)/np.log(2)).astype(int)
t=int((q-1)*q*2)
WA=np.zeros((t, n_compounds))==1
ls_nc3=[list(i)[::-1] for i in [int_to_base(j,2).zfill(q) for j in range(n_compounds)]]
k=0
for i in range(q):
for ii in range(i+1,q):
for nu in [0,1]:
for nuu in [0,1]:
for j in range(n_compounds):
WA[k,j]=True if int(ls_nc3[j][i])==nu and int(ls_nc3[j][ii])==nuu else False
k+=1
return q,t
WA=np.zeros((np.sum(primes), n_compounds))==1
past_primes=0
for prime in primes:
temp_wa=np.zeros((prime, n_compounds))==1
for x in range(prime):
ids=c_id%prime==x
temp_wa[x, ids]=True
WA[past_primes:past_primes+prime,:]=temp_wa
past_primes=past_primes+prime
return(WA.T)
def generalized_factorial(N,pw):
FT=1
for i in range(N):
FT*=(N-i)**(pw-1)
return FT
def fly_summary(n_compounds:int, differentiate:int, **kwargs):
"""
Calculate summary metrics for all pooling methods on the fly.
Returns a DataFrame with one row per method.
"""
methods = []
# Multidimensional methods (2D, 3D, 4D)