-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcanalizing_function_toolbox_v13.py
More file actions
2234 lines (1919 loc) · 96.2 KB
/
canalizing_function_toolbox_v13.py
File metadata and controls
2234 lines (1919 loc) · 96.2 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 15:53:40 2019
@author: ckadelka
#Version 13
This toolbox allows to
1) determine if a Boolean function is
a) constant
b) degenerated
c) canalizing
d) k-canalizing
2) determine the
a) canalizing depth of a Boolean function
b) the layer structure of a canaliizing Boolean function
3) generate uniformly at random
a) non-degenerated Boolean functions
a) non-canalizing Boolean functions
c) non-canalizing non-degenerated Boolean functions
d) k-canalizing Boolean functions
e) k-canalizing Boolean functions with a given layer structure
f) Boolean functions with exact canalizing depth k
g) Boolean functions with exact canalizing depth k with a given layer structure
4) generate uniformly at random Boolean networks with specific characterists (in-degree, canalization, strong connectedness)
5) obtain some basic estimates of the magnitude of various subclasses of Boolean functions
6) determine the
a) absolute bias of a Boolean function
b) average sensitivity of a Boolean function
"""
#13: proper documentation added, deleted functions that became obsolete
#1.9: new functionality added: calculate feed forward loops and feedback loops
#1.5: added is_kset_canalizing
#1.4: fixed issue with k==0 and EXACT_DEPTH==True in random_BN
#1.3: Python3.7 compatible, kis passed to random_BN can also be [0] for random networks
#1.2: added functionality to randomly create and analyze Boolean networks based on random or canalizing functions
#1.1: fixed a couple issues in is_k_canalizing, is_k_canalizing_return_inputs_outputs_corefunction and get_layerstructure_given_canalizing_outputs_and_corefunction
##Imports
import numpy as np
import matplotlib.pyplot as plt
import itertools
import networkx as nx
import random
import sympy
import pandas as pd
from collections import defaultdict
from matplotlib import colors as mcolors
try:
import cana.boolean_node
LOADED_CANA=True
except:
LOADED_CANA=False
## 0) Basics, helper functions
def tobin(x):
'''returns the binary representation (in array form) of a decimal number'''
return tobin(x//2) + [x%2] if x > 1 else [x]
def dec2bin(x,n=[]):
'''returns the binary representation (in array form) of a decimal number.
Input can be an array itself, in which case each decimal number in the
array is separately converted into a binary array.
The second input n, if specified, describes the number of positions in the
binary representation array for each number.
Example: dec2bin(10)=dec2bin(10,4)=[1,0,1,0]
dec2bin(10,6)=[0,0,1,0,1,0]'''
if type(x) in [list,np.ndarray]:
return [dec2bin(el,n) for el in x]
if n==[]:
return tobin(x)
else:
help=tobin(x)
res=[0]*(n-len(help))
res.extend(help)
return res
def bin2dec(state):
'''returns the decimal number representation of a binary state'''
n = len(state)
b = [2**i for i in range(n)]
return sum([state[n-i-1]*b[i] for i in range(n)])
def find_all_indices(array,value):
'''returns a list of all indices in array that equal a given value'''
res=[]
for i,a in enumerate(array):
if a==value:
res.append(i)
if res==[]:
raise ValueError('The value is not in the array at all.')
return res
def edgelist_to_I(edgelist):
'''input: an m x 2 array describing all edges (i.e., regulations),
with the first column describing the regulator, and the second the regulated node.
outputs:
1. I, a list of lists where
2. var, a list of all variables that show up as regulators and/or regulated nodes.
'''
regulators = np.array(edgelist)[:,0]
targets = np.array(edgelist)[:,1]
var = list(set(regulators)|set(targets))
n_var = len(var)
dict_var = dict(zip(var,range(n_var)))
I = [[] for _ in range(n_var)]
for i in range(len(regulators)):
I[dict_var[targets[i]]].append(dict_var[regulators[i]])
return I,var
def bool_to_poly(f,left_side_of_truth_table=[]):
'''
This function transforms a Boolean function from truth table format to polynomial format.
The polynomial is in non-reduced disjunctive normal form (DNF).
inputs:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
left_side_of_truth_table (optional for speed-up): the left-hand side of the Boolean truth table of size 2^n x n
output: a string of the Boolean function in disjunctive normal form (DNF)
'''
len_f = len(f)
n=int(np.log2(len_f))
if left_side_of_truth_table==[]: #to reduce run time, this should be calculated once and then passed as argument
left_side_of_truth_table = list(itertools.product([0, 1], repeat = n))
num_values = 2**n
text = []
for i in range(num_values):
if f[i]==True:
monomial = '*'.join([('x%i' % (j+1)) if entry==1 else ('(1-x%i)' % (j+1)) for j,entry in enumerate(left_side_of_truth_table[i])])
text.append(monomial)
if text!=[]:
return ' + '.join(text)
else:
return '0'
## 1) Methods to analyze Boolean functions
def is_degenerated(f):
'''
This function determines if a Boolean function contains some non-essential variables.
input: f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
output: TRUE if f contains non-essential variables, FALSE if all variables are essential.
'''
len_f = len(f)
n=int(np.log2(len_f))
for i in range(n):
dummy_add=(2**(n-1-i))
dummy=np.arange(2**n)%(2**(n-i))//dummy_add
depends_on_i=False
for j in range(2**n):
if dummy[j]==1:
continue
else:
if f[j]!=f[j+dummy_add]:
depends_on_i=True
break
if depends_on_i==False:
return True
return False
def get_essential_variables(f):
'''
This function determines the essential variables of a Boolean function
by testing exhaustively whether a given variable is essential.
input: f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
output: a list of all indices of variables, which are essential
'''
if len(f)==0:
return []
len_f = len(f)
n=int(np.log2(len_f))
essential_variables = list(range(n))
for i in range(n):
dummy_add=(2**(n-1-i))
dummy=np.arange(2**n)%(2**(n-i))//dummy_add
depends_on_i=False
for j in range(2**n):
if dummy[j]==1:
continue
else:
if f[j]!=f[j+dummy_add]:
depends_on_i=True
break
if depends_on_i==False:
essential_variables.remove(i)
return essential_variables
def get_number_essential_variables(f):
'''
This function determines the number of essential variables of a Boolean function.
input: f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
output: an integer, the number of essential variables of f
'''
return len(get_essential_variables(f))
def is_constant(f):
'''
This function checkes whether a Boolean function is constant.
input: f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
output: TRUE if f is constant, FALSE otherwise.
'''
return sum(f) in [0,len(f)]
def get_symmetry_groups(f,left_side_of_truth_table=[]):
'''
This function determines all symmetry groups of input variables for a Boolean function.
Two variables x,y are in the same symmetry group if f(x,y,z1,...,z_m) = f(y,x,z1,...,z_m) for all possible inputs to the other variables z1,...,z_m
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
left_side_of_truth_table (optional for speed-up): the left-hand side of the Boolean truth table of size 2^n x n
output: a list of m lists where m is the number of symmetry groups of f
and each inner list contains the indices of all variables in the same symmetry group.
'''
len_f = len(f)
n=int(np.log2(len_f))
if left_side_of_truth_table==[] or left_side_of_truth_table.shape[0]!=len_f:
left_side_of_truth_table = np.array(list(itertools.product([0, 1], repeat=n)))
symmetry_groups = []
left_to_check = np.ones(n)
for i in range(n):
if left_to_check[i]==0:
continue
else:
symmetry_groups.append([i])
left_to_check[i]=0
for j in range(i+1,n):
diff = sum(2**np.arange(n-i-2,n-j-2,-1))
for ii,x in enumerate(left_side_of_truth_table):
if x[i]!=x[j] and x[i]==0 and f[ii]!=f[ii+diff]:
break
else:
left_to_check[j] = 0
symmetry_groups[-1].append(j)
return symmetry_groups
def is_canalizing(f,n=-1):
'''
This function determines if a Boolean function is canalizing.
A Boolean function f(x_1,...,x_n) is canalizing if it is canalizing in at least one variable.
A Boolean function f(x_1,...,x_n) is canalizing in x_i if f(x_1,...,x_i=a,...,x_n) = b for some a,b in [0,1] and for all x_1,...,x_{i-1},x_{i+1},...,x_n in [0,1].
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
n (optional for minor speed-up): number of variables of f
output: TRUE if f is canalizing, FALSE otherwise.
'''
if type(f) == list:
f = np.array(f)
if n==-1:
n=int(np.log2(len(f)))
desired_value = 2**(n-1)
T = np.array(list(itertools.product([0, 1], repeat=n))).T
A = np.r_[T,1-T]
Atimesf = np.dot(A,f)
if np.any(Atimesf==desired_value):
return True
elif np.any(Atimesf==0):
return True
else:
return False
def is_kset_canalizing(f,k,n=-1):
'''
This function determines if a Boolean function is k-set canalizing.
A Boolean function f(x_1,...,x_n) is k-set canalizing
if there exists a set of k variables such that if this set of variables takes on certain inputs,
the output of f is determined, irrespective of the input to the n-k other variables.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
k, an integer (meaningful integers k in {0,1,...,n})
n (optional for minor speed-up): number of variables of f
output: TRUE if f is k-set canalizing, FALSE otherwise.
references:
Kadelka, C., Keilty, B., & Laubenbacher, R. (2023). Collectively canalizing Boolean functions. Advances in Applied Mathematics, 145, 102475.
'''
if type(f) == list:
F = np.array(f)
if k==0:
return is_constant(F)
if n==-1:
n=int(np.log2(len(f)))
desired_value = 2**(n-k)
T = np.array(list(itertools.product([0, 1], repeat=n))).T
A = np.r_[T,1-T]
Ak = []
for i in range(2*n):
for j in range(i+1,2*n):
if j-i == n:
continue
else:
Ak.append( np.bitwise_and(A[i,:],A[j,:]) )
Ak = []
for indices in itertools.combinations(range(2*n),k):
dummy = np.sum(A[np.array(indices),:],0)==k
if sum(dummy)==desired_value:
Ak.append(dummy)
Ak = np.array(Ak)
AktimesF = np.dot(Ak,F)
is_there_canalization = 0 in AktimesF or desired_value in AktimesF
return is_there_canalization
def get_proportion_of_collectively_canalizing_input_sets(f,k,n=-1,left_side_of_truth_table=[],verbose=False):
'''
A Boolean function f(x_1,...,x_n) is k-set canalizing
if there exists a set of k variables such that if this set of variables takes on certain inputs,
the output of f is determined, irrespective of the input to the n-k other variables.
For a given k, this function computes the probability that a k-set canalizes f.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
k, an integer (meaningful integers k in {0,1,...,n})
n (optional for minor speed-up): number of variables of f
left_side_of_truth_table (optional for speed-up): the left-hand side of the Boolean truth table of size 2^n x n
verbose (optional bool): TRUE to print all canalizing k-sets
output: TRUE if f is k-set canalizing, FALSE otherwise.
references:
Kadelka, C., Keilty, B., & Laubenbacher, R. (2023). Collectively canalizing Boolean functions. Advances in Applied Mathematics, 145, 102475.
'''
if type(f) == list:
f = np.array(f)
if k==0:
return float(is_constant(f))
if n==-1:
n=int(np.log2(len(f)))
desired_value = 2**(n-k)
if left_side_of_truth_table == []:
T = np.array(list(itertools.product([0, 1], repeat=n))).T
else:
T = np.array(left_side_of_truth_table).T
Tk = list(itertools.product([0, 1], repeat=k))
A = np.r_[T,1-T]
Ak = []
for indices in itertools.combinations(range(n),k):
for canalizing_inputs in Tk:
indices_values = np.array(indices) + n*np.array(canalizing_inputs)
dummy = np.sum(A[indices_values,:],0)==k
if sum(dummy)==desired_value:
Ak.append(dummy)
if verbose and np.dot(dummy,f) in [0,desired_value]:
print(indices,canalizing_inputs,indices_values,np.dot(dummy,f))
elif verbose:
print(indices,canalizing_inputs,sum(dummy),'a')
Ak = np.array(Ak)
is_there_canalization = np.in1d(np.dot(Ak,f),[0,desired_value])
return sum(is_there_canalization)/len(is_there_canalization)
def binom(n,k):
import scipy.special
return scipy.special.binom(n,k)
def get_canalizing_strength(f,left_side_of_truth_table=[]):
'''
This function computes the canalizing strength of a Boolean function by exhaustive enumeration (slow for functions with many variables).
The canalizing strength is a weighted average of the 1- to (n-1)-set canalizing proportions.
It is 0 for the least canalizing functions, Boolean parity functions (e.g., f= (x1 + x2 + ... + xn) % 2 == 0)
and is 1 for the most canalizing non-constant functions, nested canalizing functions with one layer (e.g. f = x1 & x2 & ... & xn)
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
left_side_of_truth_table (optional for speed-up): the left-hand side of the Boolean truth table of size 2^n x n
output: a float, describing the canalizing strength of f
references:
Kadelka, C., Keilty, B., & Laubenbacher, R. (2023). Collectively canalizing Boolean functions. Advances in Applied Mathematics, 145, 102475.
'''
nfloat = np.log2(len(f))
n = int(nfloat)
assert abs(n-nfloat)<1e-10, "F needs to be of length 2^n for some n>1"
assert n>1, "Canalizing strength is only defined for Boolean functions with n>1 inputs"
res = []
for k in range(1,n):
res.append(get_proportion_of_collectively_canalizing_input_sets(f,k,n,left_side_of_truth_table=left_side_of_truth_table))
return np.mean(np.multiply(res,2**np.arange(1,n)/(2**np.arange(1,n)-1))),res
def compute_exact_kset_canalizing_proportion_for_ncf_with_specific_layerstructure(k,layerstructure_NCF):
'''
This function implements Theorem 3.3 in [1].
It computes the exact k-set canalizing proportion for a Boolean NCF with known layer structure.
input:
k, an integer (meaningful integers k in {0,1,...,n}) where n is the number of variables of the NCF
layerstructure_NCF: [k_1,..., k_r] a list of integers describing the number of variables in each layer of an NCF,
k_i >= 1, and k_r >= 2 unless r = n = 1.
output: a float, describing the k-set canalizing proportion for the NCF with the provided layer structure
references:
[1] Kadelka, C., Keilty, B., & Laubenbacher, R. (2023). Collectively canalizing Boolean functions. Advances in Applied Mathematics, 145, 102475.
'''
r = len(layerstructure_NCF)
n = sum(layerstructure_NCF)
assert min(layerstructure_NCF) >= 1 and (layerstructure_NCF[-1]>= 2 or n==1), "each layer must contain at least one variable (the last layer at least two unless n==1)"
magnitudes = []
for t in range(r):
number_of_input_sets = 0
for c in range(1,min( k-sum(layerstructure_NCF[:t][::-2]) , layerstructure_NCF[t] )+1):
for d in range(0,min(k-sum(layerstructure_NCF[:t][::-2])-c , sum(layerstructure_NCF[:max(0,t-1)][::-2]))+1):
binom1 = binom( layerstructure_NCF[t] , c )
binom2 = binom( sum(layerstructure_NCF[:max(0,t-1)][::-2]) , d )
binom3 = binom( n-sum(layerstructure_NCF[:t+1]) , k - sum(layerstructure_NCF[:t][::-2]) - c - d)
number_of_inputs_that_canalize_for_selected_variable_set = sum([2**( k - sum(layerstructure_NCF[:t][::-2]) - j - d ) for j in range(1,c+1)])
number_of_input_sets += binom1 * binom2 * binom3 * number_of_inputs_that_canalize_for_selected_variable_set
magnitudes.append(number_of_input_sets)
#for the case where the non-canalizing output value can be reached in the evaluation process, add:
if k >= sum(layerstructure_NCF[-1::-2]):
magnitudes.append( binom( n-sum(layerstructure_NCF[-1::-2]), k-sum(layerstructure_NCF[-1::-2]) ) )
else:
magnitudes.append( 0 )
return sum(magnitudes)/(2**k * binom(n,k))#, magnitudes
#test using this code:
# k=3; kis=[2,1,2];
# print(compute_kset_canalizing_proportion_for_ncf(k,kis));
# print(can.get_canalizing_strength(can.random_k_canalizing_with_specific_layerstructure(sum(kis),kis))[1][k-1])
def is_k_canalizing(f,k,n=-1):
'''
This function determines if a Boolean function is k-canalizing.
A Boolean function f(x_1,...,x_n) is k-canalizing if it has at least k conditionally canalizing variables.
In other words, if
1. f is canalizing, and if
2. the subfunction of f when the canalizing variable takes on its non-canalizing function is canalizing, and if
3. the subfunction of the subfunction when its canalizing variable takes on its non-canalizing function is canalizing, etc.
The number of such variables is the canalizing depth of a Boolean function
and a function with canalizing depth >= k is k-canalizing.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
k, an integer (meaningful integers k in {0,1,...,n}).
Note: any function is 0-canalizing. Only NCFs are n-canalizing.
n (optional for minor speed-up): number of variables of f
output: TRUE if f is k-canalizing, FALSE otherwise.
references:
He, Q., & Macauley, M. (2016). Stratification and enumeration of Boolean functions by canalizing depth. Physica D: Nonlinear Phenomena, 314, 1-8.
Dimitrova, E., Stigler, B., Kadelka, C., & Murrugarra, D. (2022). Revealing the canalizing structure of Boolean functions: Algorithms and applications. Automatica, 146, 110630.
'''
if k>n:
return False
if k==0:
return True
if n==-1:
n=int(np.log2(len(f)))
w = sum(f) #Hamming weight of f
if w == 0 or w == 2**n: #constant f
return False
if type(f) == list:
f = np.array(f)
desired_value = 2**(n-1)
T = np.array(list(itertools.product([0, 1], repeat=n))).T
A = np.r_[T,1-T]
try: #is 1 canalized output for one of the variables
index = list(np.dot(A,f)).index(desired_value)
new_f = f[np.where(A[index]==0)[0]]
return is_k_canalizing(new_f,k-1,n-1)
except ValueError:
try: #is 0 canalized output for one of the variables
index = list(np.dot(A,1-f)).index(desired_value)
new_f = f[np.where(A[index]==0)[0]]
return is_k_canalizing(new_f,k-1,n-1)
except ValueError:
return False
def is_k_canalizing_return_inputs_outputs_corefunction(f,k,n,can_inputs=np.array([],dtype=int),can_outputs=np.array([],dtype=int)):
'''
This function determines if a Boolean function is k-canalizing.
A Boolean function f(x_1,...,x_n) is k-canalizing if it has at least k conditionally canalizing variables.
In other words, if
1. f is canalizing, and if
2. the subfunction of f when the canalizing variable takes on its non-canalizing function is canalizing, and if
3. the subfunction of the subfunction when its canalizing variable takes on its non-canalizing function is canalizing, etc.
The number of such variables is the canalizing depth of a Boolean function
and a function with canalizing depth >= k is k-canalizing.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
k, an integer (meaningful integers k in {0,1,...,n}).
Note: any function is 0-canalizing. Only NCFs are n-canalizing.
n (optional for minor speed-up): number of variables of f
output:
bool: TRUE if f is k-canalizing, FALSE otherwise.
can_inputs: list of the first k canalizing input values of f if f is k-canalizing, otherwise list of all canalizing input values
can_outputs: list of the first k canalized output values of f if f is k-canalizing, otherwise list of all canalized output values
core_function: Boolean core function in n-k variables if f is k-canalizing, otherwise Boolean core function in all m>n-k non-conditionally canalizing variables
references:
He, Q., & Macauley, M. (2016). Stratification and enumeration of Boolean functions by canalizing depth. Physica D: Nonlinear Phenomena, 314, 1-8.
Dimitrova, E., Stigler, B., Kadelka, C., & Murrugarra, D. (2022). Revealing the canalizing structure of Boolean functions: Algorithms and applications. Automatica, 146, 110630.
'''
if k==0:
return (True,can_inputs,can_outputs,f)
w = sum(f)
if w == 0 or w == 2**n: #constant f
return (False,can_inputs,can_outputs,f)
if type(f) == list:
f = np.array(f)
desired_value = 2**(n-1)
T = np.array(list(itertools.product([0, 1], repeat=n))).T
A = np.r_[T,1-T]
try: #is 1 canalized output for one of the variables
index = list(np.dot(A,f)).index(desired_value)
new_f = f[np.where(A[index]==0)[0]]
return is_k_canalizing_return_inputs_outputs_corefunction(new_f,k-1,n-1,np.append(can_inputs,int(index<n)),np.append(can_outputs,1))
except ValueError:
try: #is 0 canalized output for one of the variables
index = list(np.dot(A,1-f)).index(desired_value)
new_f = f[np.where(A[index]==0)[0]]
return is_k_canalizing_return_inputs_outputs_corefunction(new_f,k-1,n-1,np.append(can_inputs,int(index<n)),np.append(can_outputs,0))
except ValueError:
return (False,can_inputs,can_outputs,f)
def is_k_canalizing_return_inputs_outputs_corefunction_order(F,k,n,can_inputs=np.array([],dtype=int),can_outputs=np.array([],dtype=int),can_order=np.array([],dtype=int),variables=[]):
'''
This function determines if a Boolean function is k-canalizing.
A Boolean function f(x_1,...,x_n) is k-canalizing if it has at least k conditionally canalizing variables.
In other words, if
1. f is canalizing, and if
2. the subfunction of f when the canalizing variable takes on its non-canalizing function is canalizing, and if
3. the subfunction of the subfunction when its canalizing variable takes on its non-canalizing function is canalizing, etc.
The number of such conditionally canalizing variables is the canalizing depth of f,
and a function with canalizing depth >= k is k-canalizing.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
k, an integer (meaningful integers k in {0,1,...,n}).
Note: any function is 0-canalizing. Only NCFs are n-canalizing.
n (optional for minor speed-up): number of variables of f
output:
bool: TRUE if f is k-canalizing, FALSE otherwise.
can_inputs: list of the first k canalizing input values of f if f is k-canalizing, otherwise list of all canalizing input values
can_outputs: list of the first k canalized output values of f if f is k-canalizing, otherwise list of all canalized output values
core_function: Boolean core function in n-k variables if f is k-canalizing, otherwise Boolean core function in all m>n-k non-conditionally canalizing variables
can_order: list of the indices of the first k conditionally canalizing variables if f is k-canalizing,
otherwise list of the indices of all conditionally canalizing variables
references:
He, Q., & Macauley, M. (2016). Stratification and enumeration of Boolean functions by canalizing depth. Physica D: Nonlinear Phenomena, 314, 1-8.
Dimitrova, E., Stigler, B., Kadelka, C., & Murrugarra, D. (2022). Revealing the canalizing structure of Boolean functions: Algorithms and applications. Automatica, 146, 110630.
'''
if k==0:
return (True,can_inputs,can_outputs,F,can_order)
w = sum(F)
if w == 0 or w == 2**n: #constant F
return (False,can_inputs,can_outputs,F,can_order)
if type(variables)==np.ndarray:
variables = list(variables)
if variables == []:
variables = list(range(n))
if type(F) == list:
F = np.array(F)
desired_value = 2**(n-1)
T = np.array(list(itertools.product([0, 1], repeat=n))).T
A = np.r_[T,1-T]
try: #is 0 canalized output for one of the variables
index = list(np.dot(A,1-F)).index(desired_value)
newF = F[np.where(A[index]==0)[0]]
variable = variables.pop(index%n)
return is_k_canalizing_return_inputs_outputs_corefunction_order(newF,k-1,n-1,np.append(can_inputs,int(index<n)),np.append(can_outputs,0),np.append(can_order,variable),variables)
except ValueError:
try: #is 1 canalized output for one of the variables
index = list(np.dot(A,F)).index(desired_value)
newF = F[np.where(A[index]==0)[0]]
variable = variables.pop(index%n)
return is_k_canalizing_return_inputs_outputs_corefunction_order(newF,k-1,n-1,np.append(can_inputs,int(index<n)),np.append(can_outputs,1),np.append(can_order,variable),variables)
except ValueError:
return (False,can_inputs,can_outputs,F,can_order)
def find_layers(f,can_inputs=np.array([],dtype=int),can_outputs=np.array([],dtype=int),can_order=np.array([],dtype=int),variables=[],depth=0,number_layers=0):
'''
find_layers from https://github.com/ckadelka/BooleanCanalization/blob/main/find_layers.py
By [1], any non-zero Boolean function has a unqiue standard monomial form, in which
all conditionally canalizing variables are distributed into layers of importance.
This function determines the canalizing layer format of a Boolean function.
It is Algorithm 2 from [2]. For a fast implementation of Algorithm 2, see the original github repo.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
all other optional arguments must not be specified, for recursion only
output:
depth: integer k>=0, number of conditionally canalizing variables
number_layers: integer >=0, number of different layers
can_inputs: list of all k canalizing input values of f
can_outputs: list of all k canalized output values of f
core_polynomial: Boolean core polynomial in all n-k non-conditionally canalizing variables
can_order: list of the indices of all conditionally canalizing variables
references:
[1] He, Q., & Macauley, M. (2016). Stratification and enumeration of Boolean functions by canalizing depth. Physica D: Nonlinear Phenomena, 314, 1-8.
[2] Dimitrova, E., Stigler, B., Kadelka, C., & Murrugarra, D. (2022). Revealing the canalizing structure of Boolean functions: Algorithms and applications. Automatica, 146, 110630.
'''
n = int(np.log2(len(f)))
w = sum(f)
if w == 0 or w == 2**n: #constant f
return (depth,number_layers,can_inputs,can_outputs,f,can_order)
if type(variables)==np.ndarray:
variables = list(variables)
if variables == []:
variables = list(range(n))
if type(f) == list:
f = np.array(f)
desired_value = 2**(n-1)
T = np.array(list(itertools.product([0, 1], repeat=n))).T
A = np.r_[T,1-T]
indices1 = np.where(np.dot(A,f)==desired_value)[0]
indices0 = np.where(np.dot(A,1-f)==desired_value)[0]
if len(indices1)>0:
sorted_order = sorted(range(len(indices1)),key=lambda x: (indices1%n)[x])
inputs = (1-indices1//n)[np.array(sorted_order)]
outputs = np.ones(len(indices1),dtype=int)
new_canalizing_variables = []
for index in np.sort(indices1%n)[::-1]:
new_canalizing_variables.append(variables.pop(index))
new_canalizing_variables.reverse()
new_f = f[np.sort(list(set.intersection(*[] + [set(np.where(A[index]==0)[0]) for index,INPUT in zip(indices1,inputs)])))]
return find_layers(new_f,np.append(can_inputs,inputs),np.append(can_outputs,outputs),np.append(can_order,new_canalizing_variables),variables,depth+len(new_canalizing_variables),number_layers+1)
elif len(indices0):
sorted_order = sorted(range(len(indices0)),key=lambda x: (indices0%n)[x])
inputs = (1-indices0//n)[np.array(sorted_order)]
outputs = np.zeros(len(indices0),dtype=int)
new_canalizing_variables = []#variables[indices0%n]
for index in np.sort(indices0%n)[::-1]:
new_canalizing_variables.append(variables.pop(index))
new_canalizing_variables.reverse()
new_f = f[np.sort(list(set.intersection(*[] + [set(np.where(A[index]==0)[0]) for index,INPUT in zip(indices0,inputs)])))]
return find_layers(new_f,np.append(can_inputs,inputs),np.append(can_outputs,outputs),np.append(can_order,new_canalizing_variables),variables,depth+len(new_canalizing_variables),number_layers+1)
else:
return (depth,number_layers,can_inputs,can_outputs,f,can_order)
## 2) Put everything together to obtain canalizing depth, layer structure, canalized outputs, canalizing inputs as well as core function (could also calculate canalizing variables in future versions but I don't see a need)
if LOADED_CANA:
def get_input_redundancy(f,n=-1):
'''
This function computes the input redundancy of a Boolean function, defined as in [1].
Constant functions have an input redundancy of 1
because none of the inputs are needed to know the output of the function.
Parity functions (e.g., f= (x1 + x2 + ... + xn) % 2 == 0) have an input redundancy of 0
because all inputs are always needed to know the output of the function.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
output: a float in [0,1] describing the normalized input redundancy of f
references:
[1] Marques-Pita, M., & Rocha, L. M. (2013). Canalization and control in automata networks: body segmentation in Drosophila melanogaster. PloS one, 8(3), e55946.
[2] Correia, R. B., Gates, A. J., Wang, X., & Rocha, L. M. (2018). CANA: a python package for quantifying control and canalization in Boolean networks. Frontiers in physiology, 9, 1046.
'''
if n==-1:
n = int(np.log2(len(f)))
return cana.boolean_node.BooleanNode(k=n,outputs=f).input_redundancy()
def get_edge_effectiveness(f,n=-1):
'''
This function computes the edge effectiveness for each regulator of a Boolean function, defined as in [1].
Non-essential inputs have an effectiveness of 0.
Inputs, which when flipped always flip the output of a function, have an effectiveness of 1.
input:
f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
output: a list of N floats in [0,1] describing the edge effectiveness of each regulator of f
references:
[1] Marques-Pita, M., & Rocha, L. M. (2013). Canalization and control in automata networks: body segmentation in Drosophila melanogaster. PloS one, 8(3), e55946.
[2] Correia, R. B., Gates, A. J., Wang, X., & Rocha, L. M. (2018). CANA: a python package for quantifying control and canalization in Boolean networks. Frontiers in physiology, 9, 1046.
'''
if n==-1:
n = int(np.log2(len(f)))
return cana.boolean_node.BooleanNode(k=n,outputs=f).edge_effectiveness()
def get_canalizing_depth_inputs_outputs_corefunction(f):
'''obsolete, included for backward compatability, use find_layers(f)'''
n = int(np.log2(len(f)))
(NESTED_CANALIZING,can_inputs,can_outputs,corefunction) = is_k_canalizing_return_inputs_outputs_corefunction(f,n,n)
return (n,len(can_inputs),can_inputs,can_outputs,corefunction)
def get_canalizing_depth_inputs_outputs_corefunction_order(f,variables = []):
'''obsolete, included for backward compatability, use find_layers(f)'''
n = int(np.log2(len(f)))
(NESTED_CANALIZING,can_inputs,can_outputs,corefunction,can_order) = is_k_canalizing_return_inputs_outputs_corefunction_order(f,n,n,variables=variables)
return (n,len(can_inputs),can_inputs,can_outputs,corefunction,can_order)
def get_layerstructure_given_canalizing_outputs_and_corefunction(can_outputs,core_polynomial,n=-1):
'''
This function computes the canalizing layer structure of a Boolean function
given its canalized output values and core function or core polynomial, as defined in [1].
Two consecutive canalizing variables are in the same (different) layer if
they possess the same (different) canalized output value.
Input:
can_outputs: list of all k canalized output values of a Boolean function f in n variables
core_polynomial: Boolean core polynomial in all n-k non-conditionally canalizing variables
n (optional): number of variables of f
Outputs:
layerstructure: [k_1,..., k_r] a list of integers describing the number of variables in each canalizing layer of f,
k_i >= 1, and k_r >= 2 if sum(k_i)==n (i.e, if f is an NCF) unless r = n = 1.
references:
[1] Kadelka, C., Kuipers, J., & Laubenbacher, R. (2017). The influence of canalization on the robustness of Boolean networks. Physica D: Nonlinear Phenomena, 353, 39-47.
[2] Dimitrova, E., Stigler, B., Kadelka, C., & Murrugarra, D. (2022). Revealing the canalizing structure of Boolean functions: Algorithms and applications. Automatica, 146, 110630.
'''
depth = len(can_outputs)
if depth == 0:
return []
if n==-1:
n = int(np.log2(len(core_polynomial))) + depth
assert depth!=n-1,"len(can_outputs) == n-1, this is impossible because the last variable is also canalizing in this case."
if depth == n and n>1: #The last layer of Boolean NCFs has size >=2
can_outputs[-1] = can_outputs[-2]
elif is_constant(core_polynomial) and depth>1: #Exceptional case, again last layer here needs to be size >=2
can_outputs[-1] = can_outputs[-2]
layerstructure = []
size_of_layer = 1
for i in range(1,depth):
if can_outputs[i]==can_outputs[i-1]:
size_of_layer+=1
else:
layerstructure.append(size_of_layer)
size_of_layer=1
layerstructure.append(size_of_layer)
return layerstructure
def get_layerstructure_of_an_NCF_given_its_Hamming_weight(n,w):
'''
This function computes the canalizing layer structure of an NCF
with a given number of variables and a given Hamming weight.
There is a bijection between the Hamming weight
(assuming w is equivalent to 2^n-w) and the canalizing layer structure of an NCF.
Input:
n: number of variables of the NCF,
w: odd Hamming weight of the NCF, i.e., the number of 1s in the NCF in 2^n-vector form
Outputs:
r: number of layers of the NCF
layerstructure_NCF: [k_1,..., k_r] a list of integers describing the number of variables in each layer of the NCF,
k_i >= 1, and k_r >= 2 unless r = n = 1.
references:
Kadelka, C., Kuipers, J., & Laubenbacher, R. (2017). The influence of canalization on the robustness of Boolean networks. Physica D: Nonlinear Phenomena, 353, 39-47.
'''
if w==1:
r=1
layerstructure_NCF=[n]
else:
assert type(w) == int or type(w) == np.int64, 'Hamming weight must be an integer'
assert 1<=w<=2**n-1, 'Hamming weight w must satisfy, 1 <= w <= 2^n-1'
assert w%2==1, 'Hamming weight must be an odd integer since all NCFs have an odd Hamming weight.'
w_bin=dec2bin(w,n)
current_el=w_bin[0]
layerstructure_NCF=[1]
for el in w_bin[1:-1]:
if el==current_el:
layerstructure_NCF[-1]+=1
else:
layerstructure_NCF.append(1)
current_el=el
layerstructure_NCF[-1]+=1
r=len(layerstructure_NCF)
return (r,layerstructure_NCF)
## 3) Methods to randomly generate Boolean functions (uniform distribution) and Boolean networks
#Shunting-yard algorithm to evaluate expression
operators = {
"or": 1,
"and": 2,
"not": 3,
"(": 18,
")": 18
}
def eval_expr(expr, x):
op_stack = []
val_stack = []
prevToken = ""
for token in expr.split(' '):
if token == '':
continue
if token.isdigit():
val_stack.append(int(token))
elif not token in operators:
val = x[int(token[2:-1])]
val_stack.append(val)
elif token == '(':
op_stack.append(token)
elif token == ')':
while op_stack[-1] != '(':
apply_first_op(op_stack, val_stack)
op_stack.pop()
else:
while len(op_stack) > 0 and op_stack[-1] != "(" and get_precedence(op_stack[-1]) >= get_precedence(token):
apply_first_op(op_stack, val_stack)
op_stack.append(token)
prevToken = token
while len(op_stack) > 0:
apply_first_op(op_stack, val_stack)
return val_stack[0]
#Helper functions to eval_expr()
def apply_first_op(op_stack, val_stack):
assert len(op_stack) > 0
operator = op_stack.pop()
if operator == "not":
val_stack.append(int(not val_stack.pop()))
return
val1 = val_stack.pop()
val2 = val_stack.pop()
outval = 0
outval = apply_operator(operator, val1, val2)
val_stack.append(outval)
def get_precedence(operator):
return operators[operator]
def apply_operator(operator, val1, val2):
if operator == "not":
return int(not val1)
elif operator == "and":
return int(val1 and val2)
elif operator == "or":
return int(val1 or val2)
else:
print("err, unrecognized operator: ", operator)
def f_from_expression(expr):
'''
This function extracts a Boolean function from a string.
Input: a text string containing an evaluable expression
Outputs:
f: the right-hand side of a Boolean function (an array of length 2**n where n is the number of inputs)
var: a list of length n, describing the names and order of variables of f.
The order is determined by the first occurence of each variable in the input string.
Examples:
#an and-not function
print(f_from_expression('A AND NOT B'))
>> ([0, 0, 1, 0], ['A', 'B'])
#a threshold function
print(f_from_expression('x1 + x2 + x3 > 1'))
>> ([0, 0, 0, 1, 0, 1, 1, 1], ['x1', 'x2', 'x3'])
#a parity function
print(f_from_expression('(x1 + x2 + x3) % 2 == 0'))
>> ([1, 0, 0, 1, 0, 1, 1, 0], ['x1', 'x2', 'x3'])
'''
expr = expr.replace('(',' ( ').replace(')',' ) ')
expr_split = expr.split(' ')
var = []
dict_var = dict()
n_var = 0
for i,el in enumerate(expr_split):
if el not in ['',' ','(',')','and','or','not','AND','OR','NOT','&','|','~','+','-','*','%','>','>=','==','<=','<'] and not el.isdigit():
try:
new_var = dict_var[el]
except KeyError:
new_var = 'x[%i]' % n_var
dict_var.update({el:new_var})
var.append(el)
n_var += 1
expr_split[i] = new_var
elif el in ['AND','OR','NOT']:
expr_split[i] = el.lower()
expr = ' '.join(expr_split)
f = []
for x in itertools.product([0, 1], repeat = n_var):
x = list(map(bool,x))
f.append(int(eval(expr))) #x is used here "implicitly"
return f,var
def random_function(n,probability_one=0.5):
'''
This function generates a random Boolean function in n variables,
which are not guaranteed to be essential.
Inputs:
n: the number of variables
probability_one (default = 0.5): the bias of the Boolean function,
i.e., the probability of having a 1 (vs a 0) in the Boolean function.
Output: f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
'''
return np.array(np.random.random(2**n)<probability_one,dtype=int)
def random_linear_function(n):
'''
This function generates a random linear Boolean function in n variables.
Input: the number of variables
Output: f: a Boolean function as a vector, i.e., the right-hand side of a truth table (a list of length 2^n where n is the number of inputs)
'''
return f_from_expression('(%s) %% 2 == 1' % (' + '.join(['x%i' % i if random.random()>0.5 else '(1 + x%i)' % i for i in range(n)])))[0]
def random_non_degenerated_function(n,probability_one=0.5):
'''
This function generates a random non-degenerated Boolean function in n variables.
That is, it generates a Boolean function which possesses only essential variables.
Inputs:
n: the number of variables
probability_one (default = 0.5): the bias of the Boolean function,
i.e., the probability of having a 1 (vs a 0) in the Boolean function.