-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFast_functions.py
More file actions
2359 lines (2037 loc) · 84.8 KB
/
Fast_functions.py
File metadata and controls
2359 lines (2037 loc) · 84.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
import numpy as np
import re
import itertools
import math
import pandas as pd
import os
import time
import string
import shutil
import scipy
from sklearn.linear_model import ElasticNet
from scipy.optimize import minimize
from scipy.optimize import nnls
from sklearn.linear_model import Lasso
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 format_time(seconds):
"""Convert seconds to days, hours, minutes, seconds format."""
days = int(seconds // 86400)
hours = int((seconds % 86400) // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
parts = []
if days > 0:
parts.append(f"{days}d")
if hours > 0:
parts.append(f"{hours}h")
if minutes > 0:
parts.append(f"{minutes}m")
parts.append(f"{secs}s")
return " ".join(parts)
def str_to_tuple(string, delimiter='-'):
return tuple(string.split(delimiter))
def tuple_to_str(tuple_type, delimiter='-'):
return delimiter.join(map(str,tuple_type))
# Utility: Generate a sparse random array of length L with p nonzero elements (values in [0, 3))
def sparse_uniform_array(L, p, low=0.0, high=3.0, random_state=None):
"""
Generate an array of length L with exactly p nonzero elements, each drawn uniformly from [low, high).
The positions of the nonzero elements are chosen at random.
"""
if p > L:
raise ValueError("p cannot be greater than L")
rng = np.random.default_rng(random_state)
arr = np.zeros(L)
if p > 0:
idx = rng.choice(L, size=p, replace=False)
arr[idx] = rng.uniform(low, high, size=p)
return arr
def sweep_fly_summary(start, stop, step, start_diff, stop_diff, step_diff, directory, folder_N=False, folder_diff=False, checks_hierarchical=1000, max_prev=0.1, **kwargs):
"""
Calculate fly_summary for a range of N and differentiation values and save as CSV files.
Parameters:
-----------
start : int
Starting value for N
stop : int
Stopping value for N (inclusive)
step : int
Step size for N increments
start_diff : int
Starting value for differentiation
stop_diff : int
Stopping value for differentiation (inclusive)
step_diff : int
Step size for differentiation increments
directory : str
Base directory where files will be saved
folder_N : bool, default=False
If True, create a folder for each N value
folder_diff : bool, default=False
If True, create folders for each differentiation value
checks_hierarchical : int, default=1000
Number of checks for hierarchical method
"""
# Create base directory if it doesn't exist
os.makedirs(directory, exist_ok=True)
# Start overall timer
start_time = time.time()
random_filename_re = re.compile(r"^Random_diff_(?P<diff>[0-9]+)_NS_(?P<ns>[0-9]+)_NW_(?P<nw>[0-9.]+)_MS_(?P<ms>[0-9.]+)_PC_(?P<pc>[0-9.]+)_ME_(?P<me>[0-9.]+)\.txt$")
def parse_random_metrics(candidates, N, diff):
for cand in candidates:
if not os.path.isdir(cand):
continue
for fname in os.listdir(cand):
match = random_filename_re.match(fname)
if not match:
continue
parts = match.groupdict()
if int(parts['diff']) != diff or int(parts['ns']) != N:
continue
nw = float(parts['nw'])
ms = float(parts['ms'])
pc = float(parts['pc'])
me = float(parts['me'])
extra = max(me - nw, 0.0)
return {
'Pooling strategy': 'Random',
'Max experiments': me,
'Max samples per pool': ms,
'N pools': nw,
'Percentage check': pc,
'Max extra experiments': extra,
'Mean steps': 1 + pc/100.0
}
return None
# Loop over N values
for N in range(start, stop + 1, step):
N_start_time = time.time()
# Determine N-level directory
if folder_N:
N_dir = os.path.join(directory, f'N_{N}')
os.makedirs(N_dir, exist_ok=True)
else:
N_dir = directory
stop_diffo=stop_diff if stop_diff>0 else int(max_prev*N)+2
# Loop over differentiation values
for diff in range(start_diff, stop_diffo + 1, step_diff):
if diff>max_prev*N:
break
# Determine diff-level directory
if folder_diff:
if folder_N:
diff_dir = os.path.join(N_dir, f'diff_{diff}')
else:
diff_dir = os.path.join(directory, f'diff_{diff}')
os.makedirs(diff_dir, exist_ok=True)
else:
diff_dir = N_dir
# Calculate metrics
df = fly_summary(N, diff, checks_hierarchical=checks_hierarchical)
# If a random design summary file exists, append its metrics
candidate_dirs = list(dict.fromkeys([
diff_dir,
os.path.join(N_dir, f'diff_{diff}'),
os.path.join(directory, f'N_{N}', f'diff_{diff}')
]))
random_row = parse_random_metrics(candidate_dirs, N, diff)
if random_row is not None:
df = pd.concat([df, pd.DataFrame([random_row])], ignore_index=True)
numeric_cols = df.select_dtypes(include=[np.number]).columns
df[numeric_cols] = df[numeric_cols].round(2)
# Save to CSV
filename = f'Summary_N_{N}_diff_{diff}.csv'
filepath = os.path.join(diff_dir, filename)
df.to_csv(filepath, index=False)
# Print time elapsed for this N
N_elapsed = time.time() - N_start_time
print(f"Completed N={N}, time elapsed {format_time(N_elapsed)}")
# Print total completion time
total_elapsed = time.time() - start_time
print(f"\nAll calculations completed, total time elapsed {format_time(total_elapsed)}")
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.prod(primes)
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
try:
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
except:
npc=nprimes
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
try:
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
except:
npc=nprimes
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 (WA.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 (WA.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, checks_hierarchical=65, **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)
for n_dims in [2, 3, 4]:
ls_dims=get_params_multidims(n_compounds, n_dims)
arr_dims=np.array(ls_dims)
method_name = f'multidim-{n_dims}'
PCF=np.ones_like(arr_dims).astype(float)
if differentiate>=np.max(arr_dims):
PCT=100
elif differentiate==1:
PCT=0
else:
for i in range(differentiate):
NG=(arr_dims-i-1)
NT=(n_compounds-i-1)
PC=NG/NT
PCF*=PC
PCT=100*(1-np.sum(PCF))
MEE=np.min([differentiate**n_dims, generalized_factorial(differentiate, n_dims), n_compounds ])-1
method_dict = {
'Pooling strategy': method_name,
'Max experiments': np.sum(arr_dims)+MEE,
'Max samples per pool': np.prod(arr_dims)/np.min(arr_dims),
'N pools': np.sum(arr_dims),
'Percentage check': PCT,
'Max extra experiments': MEE,
'Mean steps': 1+PCT/100
}
methods.append(method_dict)
# Matrix method - copy of 2D
if n_dims == 2:
matrix_dict = method_dict.copy()
matrix_dict['Pooling strategy'] = 'Matrix'
methods.append(matrix_dict)
# Binary method
method_name = 'Binary'
if differentiate>=2:
PC=100
MEE=n_compounds
else:
PC=0
MEE=0
methods.append({
'Pooling strategy': method_name,
'Max experiments': int(np.ceil(np.log2(n_compounds)))+MEE,
'Max samples per pool': int(np.ceil(n_compounds/2)),
'N pools': int(np.ceil(np.log2(n_compounds))),
'Percentage check': PC,
'Max extra experiments': MEE,
'Mean steps': 1+PC/100
})
# STD method
method_name = 'STD'
q,k = get_STD_params(n_compounds, differentiate)
methods.append({
'Pooling strategy': method_name,
'Max experiments': int(q*k),
'Max samples per pool': int(np.ceil(n_compounds/q)),
'N pools':int(q*k),
'Percentage check': 0,
'Max extra experiments': 0,
'Mean steps': 1
})
# Chinese Remainder method
method_name = 'Chinese remainder'
primez = get_chinese_prameters(n_compounds, differentiate)
methods.append({
'Pooling strategy': method_name,
'Max experiments': np.sum(primez),
'Max samples per pool': n_compounds/np.min(primez),
'N pools': np.sum(primez),
'Percentage check': 0,
'Max extra experiments': 0,
'Mean steps': 1
})
# Chinese Remainder backtrack method
method_name = 'Ch. rm. bktrk'
primez = get_chinese_prameters(n_compounds, differentiate, backtrack=True)
methods.append({
'Pooling strategy': method_name,
'Max experiments': np.sum(primez),
'Max samples per pool': n_compounds/np.min(primez),
'N pools': np.sum(primez),
'Percentage check': 0,
'Max extra experiments': 0,
'Mean steps': 1
})
# Chinese Remainder special method (only for differentiate 2 or 3)
if differentiate in [2, 3]:
method_name = 'Chinese special'
q,t = get_chinese_prameters(n_compounds, differentiate, special_diff=True)
if differentiate==2:
MS=3**q
elif differentiate==3:
MS=2**(q-2)
methods.append({
'Pooling strategy': method_name,
'Max experiments': t,
'Max samples per pool':MS,
'N pools': t,
'Percentage check': 0,
'Max extra experiments': 0 ,
'Mean steps':1
})
methods.append({
'Pooling strategy': method_name,
'Max experiments': t,
'Max samples per pool':MS,
'N pools': t,
'Percentage check': 0,
'Max extra experiments': 0,
'Mean steps':1
})
method_name = 'Hierarchical'
metricas=calculate_metrics_hierarchical_fast(n_compounds, differentiate, checks=checks_hierarchical)
methods.append({
'Pooling strategy': method_name,
'Max experiments': metricas[0],
'Max samples per pool':metricas[1],
'N pools': metricas[2],
'Percentage check': metricas[3],
'Max extra experiments': np.round(metricas[4],2),
'Mean steps': metricas[5]
})
df = pd.DataFrame(methods)
# Round all numeric columns to 2 decimal places
numeric_cols = df.select_dtypes(include=[np.number]).columns
df[numeric_cols] = df[numeric_cols].round(2)
return df
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 pick_rand_pos(n_compounds,differentiate,max_checks=1e3):
MC=0
MP=1
mp=0
scaler=1
ls_combs=[]
ls_diffs=[]
difo=differentiate
while (MC<max_checks or MP>mp) and difo>0:
MCI=math.comb(n_compounds,differentiate)
MC+=MCI
mp=MCI/MC
ls_combs.append(MCI)
ls_diffs.append(difo)
difo-=1
ls_posi=[]
probi=np.array(ls_combs, dtype=float)
probi/=np.sum(probi)
differis=np.random.choice(ls_diffs, int(max_checks*scaler), p=probi)
for differo in differis:
rnd_pos=np.random.choice(np.arange(n_compounds), differo, replace=False)
ls_posi.append(rnd_pos)
return ls_posi
def iterative_splitter(id_samps, id_positives, ratio):
if len(id_samps)<=ratio:
return(len(id_samps))
pools=list(split(id_samps, ratio))
partials=0
for pool in pools:
if len(set(pool).intersection(id_positives))>0:
partials+=iterative_splitter(pool,id_positives,ratio)
return(ratio+partials)
def uneven_wrapper(n_samps, differentiate=-1):
if differentiate==-1:
differentiate=np.floor(n_samps/2)
list_of_lists=[]
def uneven_splits_maker(n_samps, previous_l):
if n_samps<2:
pass
if len(previous_l)==0:
C1=n_samps
else:
C1=previous_l[-1]
MS=np.min([differentiate*5, C1 , n_samps])
rationi=np.arange(2,MS+1)
invariationi=n_samps/rationi
linvariationi=np.array(list(set(invariationi.astype(int))))
variationi=n_samps/linvariationi
ratios=[rationi[np.argmin(np.abs(rationi-i))] for i in variationi ]
for ratio in ratios:
this_l=previous_l.copy()
this_l.append(int(ratio))
list_of_lists.append(this_l)
uneven_splits_maker(np.ceil(n_samps/ratio), this_l)
uneven_splits_maker(n_samps,[])
return(list_of_lists)
def iterative_uneven_splitter(id_samps, id_positives, ratios):
if len(ratios)==1:
ratio=ratios[0]
ratios=[np.inf]
else:
ratio=ratios[0]
ratios=ratios[1:]
if len(id_samps)<=ratio:
return(len(id_samps))
pools=list(split(id_samps, ratio))
partials=0
for pool in pools:
if len(set(pool).intersection(id_positives))>0:
partials+=iterative_uneven_splitter(pool,id_positives,ratios)
return(ratio+partials)
def calculate_metrics_hierarchical_fast(n_compounds, differentiate:int, checks=1e4, keep_ratios_constant=False, **kwargs):
id_samps=np.arange(n_compounds)
details={}
posiz=pick_rand_pos(n_compounds, differentiate, checks)
if keep_ratios_constant:
BM=[0,np.inf]
for ratiof in np.arange(2,np.ceil(np.sqrt(n_compounds))):
ratio=int(ratiof)
NP=0
FM=0
for id_pos in posiz:
posx=np.array(id_pos).reshape(-1,1)
measures=iterative_splitter(id_samps,posx,ratio)
FM+=measures
NP+=1
layers=int(np.ceil(np.log(n_compounds)/np.log(ratio)))
MC=int(np.ceil(n_compounds/ratio))
details.update({ratio:[BM[1], MC, BM[0], int(np.round((NP-1)/(NP),2)*100), BM[1]-BM[0],layers]})
if FM/NP<BM[1]:
BM=[ratio,FM/NP]
layers=int(np.ceil(np.log(n_compounds)/np.log(BM[0])))
MC=int(np.ceil(n_compounds/BM[0]))
return([BM[1], MC, BM[0], int(np.round((NP-1)/(NP),2)*100), BM[1]-BM[0],layers, details ])
else:
BM=[[0],np.inf]
if 'ls_splits' in kwargs.keys():
list_splits=[kwargs['ls_splits']]
else:
list_splits=uneven_wrapper(n_compounds, differentiate)
ls_id=0
for splito in list_splits:
NP=0
FM=0
for id_pos in posiz:
posx=np.array(id_pos)
measures=iterative_uneven_splitter(id_samps,posx,splito)
FM+=measures
NP+=1
layers=len(splito)+1
MC=int(np.ceil(n_compounds/splito[0]))
#details.update({ls_id:[FM/NP, MC, splito, int(np.round((NP-1)/(NP),2)*100), FM/NP-splito[0],layers]})
ls_id+=1
if FM/NP<BM[1]:
BM=[splito,FM/NP]
layers=len(BM[0])+1
MC=int(np.ceil(n_compounds/BM[0][0]))
return([BM[1], MC, BM[0], int(np.round((NP-1)/(NP),2)*100), BM[1]-BM[0][0],layers])
# Utility functions from rand_WA_fast.py
def get_max_C(n_compounds, max_compounds):
return int(n_compounds/2) if max_compounds==0 else max_compounds
def get_min_C(n_compounds, MC):
return int(np.sqrt(n_compounds)) if int(np.sqrt(n_compounds))<MC else int(MC/2)
def get_min_W(n_compounds):
return int(np.log2(n_compounds)*0.5)
def get_max_W(n_compounds):
return int(2*np.sqrt(n_compounds))
def mean_metrics_fast(well_assigner, differentiate, max_checks=1e0, scaler=1e3, mp=1e-5, **kwargs):
BT=well_assigner.shape[1]
n_compounds=well_assigner.shape[0]
MC=0
MP=1
ls_combs=[]
ls_diffs=[]
difo=differentiate
while (MC<max_checks*scaler or MP>mp) and difo>0:
MCI=math.comb(n_compounds,differentiate)
MC+=MCI
mp=MCI/MC
ls_combs.append(MCI)
ls_diffs.append(difo)
difo-=1
counts=[]
probi=np.array(ls_combs, dtype=float)
probi/=np.sum(probi)
differis=np.random.choice(ls_diffs, int(max_checks*scaler), p=probi)
#differo=differentiate
#for _ in range(int(max_checks*scaler)):
MC=np.max([int(max_checks*scaler/10+5), n_compounds+1])
for differo in differis:
rnd_pos=np.random.choice(np.arange(n_compounds), differo, replace=False)
readout=np.any(well_assigner[rnd_pos], axis=0)
decoded=fast_decode(well_assigner=well_assigner, differentiate=differentiate,
readout=readout, max_checks=MC)
try:
decoded_set=set([x for xx in decoded for x in xx])
NC0=len(decoded_set)
NC=np.min([NC0,len(decoded)])
except:
NC=len(decoded)
counts.append(NC)
counts=np.array(counts)
#ET=np.max(counts-1)#/len(counts)
ET=np.sum(counts)/len(counts)
ET =ET if ET>1 else 0#if ET<well_assigner.shape[0] else well_assigner.shape[0]
ER=np.sum(counts>1)/np.sum(counts>0)
rounds=ER+1
p_check=np.round(ER*100)
return BT+ET, ET, rounds, p_check
def decode_precomp(well_assigner:np.array, differentiate:int,
scrambler:dict, readout:np.ndarray, max_differentiate=-1, sweep=False, **kwargs) -> list:
if differentiate==0:
return(True,well_assigner, np.array([1]*well_assigner.shape[0]))
if max_differentiate<1:
N=well_assigner.shape[0]
sc_list=np.arange(N).tolist()
for i in range(differentiate):
diff=i+1
if diff ==1:
full_well_assigner=well_assigner.copy()
else:
this_sc=scrambler[diff]
#print(this_sc)
#print(well_assigner)
#print(diff)
full_well_assigner=np.concatenate((full_well_assigner,np.any(well_assigner[this_sc], axis=1)))
sc_list.extend(this_sc.tolist())
#outcomes,_=np.unique(full_well_assigner, axis=0, return_counts=True)
if sweep:
outcome_dict={}
outcomes=np.unique(full_well_assigner, axis=0, return_counts=False).astype(int)
for outcome in outcomes:
idxs = np.all(outcome == full_well_assigner, axis=1)
outcome_dict.update({tuple_to_str(tuple(outcome)):list(itertools.compress(sc_list,idxs))})
return outcome_dict
else:
idxs = np.all(readout == full_well_assigner, axis=1)
return list(itertools.compress(sc_list,idxs))
else:
full_od={}
N=well_assigner.shape[0]
sc_list=np.arange(N).tolist()
for differentiate in range(max_differentiate):
diff=differentiate+1
if diff ==1:
full_well_assigner=well_assigner.copy()
else:
this_sc=scrambler[diff]
print(this_sc)
print(well_assigner)
print(diff)
full_well_assigner=np.concatenate((full_well_assigner,np.any(well_assigner[this_sc], axis=1)))
sc_list.extend(this_sc.tolist())
#outcomes,_=np.unique(full_well_assigner, axis=0, return_counts=True)
if sweep:
outcome_dict={}
outcomes=np.unique(full_well_assigner, axis=0, return_counts=False).astype(int)
for outcome in outcomes:
idxs=np.prod(outcome==full_well_assigner, axis=1)
outcome_dict.update({tuple_to_str(tuple(outcome)):list(itertools.compress(sc_list,idxs))})
full_od.update({diff:outcome_dict})
else:
idxs=np.prod(readout==full_well_assigner, axis=1)
full_od.update({diff:list(itertools.compress(sc_list,idxs))})
return full_od
# Random Design Functions from rand_WA_fast.py
def fast_decode(well_assigner:np.array, differentiate:int, readout:np.ndarray,
max_checks=1e4, **kwargs):
WA=well_assigner
n_pools=WA.shape[1]
if np.max(readout)>1 or len(readout)!=n_pools:
readout_bin_ls = [1 if i in readout else 0 for i in range(n_compounds)]
readout_bl=np.array(readout_bin_ls)
else:
readout_bl=readout
mask = ~np.any((WA == 1) & (readout_bl == 0), axis=1)
original_indices = np.where(mask)[0]
filtered_WA = WA[mask]
n_compounds=filtered_WA.shape[0]
if n_compounds<differentiate:
differentiate=n_compounds
if n_compounds<2:
if n_compounds==1:
decoded=[original_indices[0]]
else:
decoded=[]
else:
MC=0
MP=1
ls_combs=[]
ls_diffs=[]
difo=differentiate
while (MC<max_checks or MP>mp) and difo>0:
MCI=math.comb(n_compounds,differentiate)
MC+=MCI
mp=MCI/MC
ls_combs.append(MCI)
ls_diffs.append(difo)
difo-=1
if MC>max_checks:
decoded = [int(original_indices[idx]) for idx in range(len(original_indices))]
else:
scrambler={1:np.arange(n_compounds)}
for j in range(2,differentiate+1):
scrambler.update({j:np.array(list(itertools.combinations(np.arange(n_compounds),j)))})
decoded_pre=decode_precomp(well_assigner=filtered_WA, differentiate= differentiate, scrambler=scrambler,
readout=readout_bl)
decoders = [combination if isinstance(combination, list) else [combination] for combination in decoded_pre]
decoded = [[int(original_indices[idx]) for idx in combination] for combination in decoders]
return decoded
def find_rand_params_precomp(n_compounds:int, n_compounds_per_well=0, n_wells=0, guesses=0,
max_compounds=0, max_redundancy=4, min_redundancy=1, differentiate=1, **kwargs):
skip_compounds=True
skip_wells=True
if n_compounds_per_well==0:
skip_compounds=False
if n_wells==0:
skip_wells=False
if guesses==0:
guesses=n_compounds
MC= get_max_C(n_compounds, max_compounds)
mc=get_min_C(n_compounds, MC)
arr_comp=np.arange(int(mc),int(MC+1))
mw=get_min_W(n_compounds)
MW=get_max_W(n_compounds)
while MW-mw<10:
mw=int(abs(mw-1))
MW=int(MW+1)
arr_wells=np.arange(mw,MW+1)
min_tests=np.inf
N_tries=0
for comp in arr_comp:
if skip_compounds:
comp=n_compounds_per_well