-
Notifications
You must be signed in to change notification settings - Fork 14
/
models_phenom.py
1426 lines (1173 loc) · 57.1 KB
/
models_phenom.py
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
# AUTOGENERATED! DO NOT EDIT! File to edit: ../source_nbs/lib_nbs/models_phenom.ipynb.
# %% auto 0
__all__ = ['models_phenom']
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 2
import numpy as np
from stochastic.processes.noise import FractionalGaussianNoise as FGN
from .utils_trajectories import gaussian
import warnings
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 5
class models_phenom():
def __init__(self):
'''
This class handles the generation of trajectories from different theoretical models.
'''
# We define here the bounds of the anomalous exponent and diffusion coefficient
self.bound_D = [1e-12, 1e6]
self.bound_alpha = [0, 1.999]
# We also define the value in which we consider directed motion
self.alpha_directed = 1.9
# Diffusion state labels: the position of each type defines its numerical label
# i: immobile/trapped; c: confined; f: free-diffusive (normal and anomalous); d: directed
self.lab_state = ['i', 'c', 'f', 'd']
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 7
class models_phenom(models_phenom):
@staticmethod
def disp_fbm(alpha : float,
D : float,
T: int,
deltaT : int = 1):
''' Generates normalized Fractional Gaussian noise. This means that, in
general:
$$
<x^2(t) > = 2Dt^{alpha}
$$
and in particular:
$$
<x^2(t = 1)> = 2D
$$
Parameters
----------
alpha : float in [0,2]
Anomalous exponent
D : float
Diffusion coefficient
T : int
Number of displacements to generate
deltaT : int, optional
Sampling time
Returns
-------
numpy.array
Array containing T displacements of given parameters
'''
# Generate displacements
disp = FGN(hurst = alpha/2).sample(n = T)
# Normalization factor
disp *= np.sqrt(T)**(alpha)
# Add D
disp *= np.sqrt(2*D*deltaT)
return disp
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 18
class models_phenom(models_phenom):
@staticmethod
def _constraint_alpha(alpha_1, alpha_2, epsilon_a):
''' Defines the metric for constraining the changes in anomalous
exponent'''
return alpha_1 - alpha_2 < epsilon_a
@staticmethod
def _constraint_d(d1, d2, gamma_d):
''' Defines the metric for constraining the changes in anomalous
exponent'''
if gamma_d < 1:
return d2 > d1*gamma_d
if gamma_d > 1:
return d2 < d1*gamma_d
@staticmethod
def _sample_diff_parameters(alphas : list, # List containing the parameters to sample anomalous exponent in state (adapt to sampling function)
Ds : list, # List containing the parameters to sample the diffusion coefficient in state (adapt to sampling function).
num_states : int, # Number of diffusive states.
epsilon_a : float, # Minimum distance between anomalous exponents of various states.
gamma_d : float, # Factor between diffusion coefficient of various states.
) :
'''
Given information of the anomalous exponents (alphas), diffusion coefficients (Ds), the function
samples these from a bounded Gaussian distribution with the indicated constraints (epsilon_a,
gamma_d). Outputs the list of demanded alphas and Ds.
Parameters
----------
alphas : list
List containing the parameters to sample anomalous exponent in state (adapt to sampling function).
Ds : list
List containing the parameters to sample the diffusion coefficient in state (adapt to sampling function).
num_states : int
Number of diffusive states.
epsilon_a : float
Minimum distance between anomalous exponents of various states.
epsilon workflow: we check val[i] - val[i-1] < epsilon
if you want that val[i] > val[i-1]: epsilon has to be positive
if you want that val[i] < val[i-1]: epsilon has to be negative
if you don't care: epsilon = 0
gamma_d : float
Factor between diffusion coefficient of various states.
gamma workflow:
for gamma < 1: val[i] < val[i-1]*gamma
for gamma > 1: val[i] > val[i-1]*gamma
for gamma = 1: no check
Returns
-------
:alphas_traj (list): list of anomalous exponents
:Ds_traj (list): list of diffusion coefficients
'''
alphas_traj = []
Ds_traj = []
for i in range(num_states):
# for the first state we just sample normally
if i == 0:
alphas_traj.append(float(gaussian(alphas[i], bound = models_phenom().bound_alpha)))
Ds_traj.append(float(gaussian(Ds[i], bound = models_phenom().bound_D)))
# For next states we take into account epsilon distance between diffusion
# parameter
else:
## Checking alpha
alpha_state = float(gaussian(alphas[i], bound = models_phenom().bound_alpha))
D_state = float(gaussian(Ds[i], bound = models_phenom().bound_D))
if epsilon_a[i-1] != 0:
idx_while = 0
while models_phenom()._constraint_alpha(alphas_traj[-1], alpha_state, epsilon_a[i-1]):
#alphas_traj[-1] - alpha_state < epsilon_a[i-1]:
alpha_state = float(gaussian(alphas[i], bound = models_phenom().bound_alpha))
idx_while += 1
if idx_while > 100: # check that we are not stuck forever in the while loop
raise FileNotFoundError(f'Could not find correct alpha for state {i} in 100 steps. State distributions probably too close.')
alphas_traj.append(alpha_state)
## Checking D
if gamma_d[i-1] != 1:
idx_while = 0
while models_phenom()._constraint_d(Ds_traj[-1], D_state, gamma_d[i-1]):
D_state = float(gaussian(Ds[i], bound = models_phenom().bound_D))
idx_while += 1
if idx_while > 100: # check that we are not stuck forever in the while loop
raise FileNotFoundError(f'Could not find correct D for state {i} in 100 steps. State distributions probably too close.')
Ds_traj.append(D_state)
return alphas_traj, Ds_traj
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 26
class models_phenom(models_phenom):
@staticmethod
def _single_state_traj(T :int = 200,
D : float = 1,
alpha : float = 1,
L : float = None,
deltaT : int = 1,
dim : int = 2):
'''
Generates a single state trajectory with given parameters.
Parameters
----------
T : int
Length of the trajectory
D : float
Diffusion coefficient
alpha : float
Anomalous exponent
L : float
Length of the box acting as the environment
deltaT : int, optional
Sampling time
dim : int
Dimension of the walk (can be 2 or 3)
Returns
-------
tuple
- pos: position of the particle
- labels: anomalous exponent, D and state at each timestep. State is always free here.
'''
# Trajectory displacements
disp_d = []
for d in range(dim):
disp_d.append(models_phenom().disp_fbm(alpha, D, T))
# Labels
lab_diff_state = np.ones(T)*models_phenom().lab_state.index('f') if alpha < models_phenom().alpha_directed else np.ones(T)*models_phenom().lab_state.index('d')
labels = np.vstack((np.ones(T)*alpha,
np.ones(T)*D,
lab_diff_state
)).transpose()
# If there are no boundaries
if not L:
pos = np.vstack([np.cumsum(disp)-disp[0] for disp in disp_d]).transpose()
return pos, labels
# If there are, apply reflecting boundary conditions
else:
pos = np.zeros((T, dim))
# Initialize the particle in a random position of the box
pos[0, :] = np.random.rand(dim)*L
for t in range(1, T):
if dim == 2:
pos[t, :] = [pos[t-1, 0]+disp_d[0][t],
pos[t-1, 1]+disp_d[1][t]]
elif dim == 3:
pos[t, :] = [pos[t-1, 0]+disp_d[0][t],
pos[t-1, 1]+disp_d[1][t],
pos[t-1, 2]+disp_d[2][t]]
# Reflecting boundary conditions
while np.max(pos[t, :])>L or np.min(pos[t, :])< 0:
pos[t, pos[t, :] > L] = pos[t, pos[t, :] > L] - 2*(pos[t, pos[t, :] > L] - L)
pos[t, pos[t, :] < 0] = - pos[t, pos[t, :] < 0]
return pos, labels
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 33
class models_phenom(models_phenom):
def single_state(self,
N:int = 10,
T:int = 200,
Ds:list = [1, 0],
alphas:list = [1, 0],
L:float = None,
dim:int = 2):
'''
Generates a dataset made of single state trajectories with given parameters.
Parameters
----------
N : int, list
Number of trajectories in the dataset
T : int
Length of the trajectory
Ds : float
If list, mean and variance from which to sample the diffusion coefficient. If float, we consider variance = 0.
alphas : float
If list, mean and variance from which to sample the anomalous exponent. If float, we consider variance = 0.
L : float
Length of the box acting as the environment
deltaT : int, optional
Sampling time
dim : int
Dimension of the walk (can be 2 or 3)
Returns
-------
tuple
- positions: position of the N trajectories.
- labels: anomalous exponent, D and state at each timestep. State is always free here.
'''
positions = np.zeros((T, N, dim))
labels = np.zeros((T, N, 3))
for n in range(N):
alpha_traj = gaussian(alphas, bound = self.bound_alpha)
D_traj = gaussian(Ds, bound = self.bound_D)
# Get trajectory from single traj function
pos, lab = self._single_state_traj(T = T,
D = D_traj,
alpha = alpha_traj,
L = L,
dim = dim
)
positions[:, n, :] = pos
labels[:, n, :] = lab
return positions, labels
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 43
class models_phenom(models_phenom):
@staticmethod
def _multiple_state_traj(T = 200,
M = [[0.95 , 0.05],[0.05 ,0.95]],
Ds = [1, 0.1],
alphas = [1, 1],
L = None,
deltaT = 1,
return_state_num = False,
init_state = None
):
'''
Generates a 2D multi state trajectory with given parameters.
Parameters
----------
T : int
Length of the trajectory
M : list, array
Transition matrix between diffusive states.
Ds : list
Diffusion coefficients of the diffusive states. Must have as many Ds as states defined by M.
alphas : list
Anomalous exponents of the diffusive states. Must have as many alphas as states defined by M.
L : float
Length of the box acting as the environment
deltaT : int, optional
Sampling time
return_state_num : bool
If True, returns as label the number assigned to the state at each time step.
init_state : bool
If True, the particle starts in state 0. If not, sample initial state.
Returns
-------
tuple
- pos: position of the particle
- alphas_t: anomalous exponent at each step
- Ds_t: diffusion coefficient at each step.
- label_diff_state: particle's state (can be either free or directed for alpha ~ 2) at each step.
- state (optional): state label at each step.
'''
# transform lists to numpy if needed
if isinstance(M, list):
M = np.array(M)
if isinstance(Ds, list):
Ds = np.array(Ds)
if isinstance(alphas, list):
alphas = np.array(alphas)
pos = np.zeros((T, 2))
if L: pos[0,:] = np.random.rand(2)*L
# Diffusing state of the particle
state = np.zeros(T).astype(int)
if init_state is None:
state[0] = np.random.randint(M.shape[0])
else: state[0] = init_state
# Init alphas, Ds
alphas_t = np.array(alphas[state[0]]).repeat(T)
Ds_t = np.array(Ds[state[0]]).repeat(T)
# Trajectory displacements
dispx, dispy = [models_phenom().disp_fbm(alphas_t[0], Ds_t[0], T),
models_phenom().disp_fbm(alphas_t[0], Ds_t[0], T)]
for t in range(1, T):
pos[t, :] = [pos[t-1, 0]+dispx[t], pos[t-1, 1]+dispy[t]]
# at each time, check new state
state[t] = np.random.choice(np.arange(M.shape[0]), p = M[state[t-1], :])
if state[t] != state[t-1]:
alphas_t[t:] = np.array(alphas[state[t]]).repeat(T-t)
Ds_t[t:] = np.array(Ds[state[t]]).repeat(T-t)
# Recalculate new displacements for next steps
if len(dispx[t:]) > 1:
dispx[t:], dispy[t:] = [models_phenom().disp_fbm(alphas_t[t], Ds_t[t], T-t),
models_phenom().disp_fbm(alphas_t[t], Ds_t[t], T-t)]
else:
dispx[t:], dispy[t:] = [np.sqrt(2*Ds[state[t]]*deltaT)*np.random.randn(),
np.sqrt(2*Ds[state[t]]*deltaT)*np.random.randn()]
if L is not None:
# Reflecting boundary conditions
while np.max(pos[t, :])>L or np.min(pos[t, :])< 0:
pos[t, pos[t, :] > L] = pos[t, pos[t, :] > L] - 2*(pos[t, pos[t, :] > L] - L)
pos[t, pos[t, :] < 0] = - pos[t, pos[t, :] < 0]
# Define state of particles based on values of alphas: either free or directed
label_diff_state = np.zeros_like(alphas_t)
label_diff_state[alphas_t < models_phenom().alpha_directed] = models_phenom().lab_state.index('f')
label_diff_state[alphas_t >= models_phenom().alpha_directed] = models_phenom().lab_state.index('d')
if return_state_num:
return pos, np.array((alphas_t,
Ds_t,
label_diff_state,
state)).transpose()
else:
return pos, np.array((alphas_t,
Ds_t,
label_diff_state)).transpose()
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 47
class models_phenom(models_phenom):
def multi_state(self,
N = 10,
T = 200,
M: np.array = [[0.9 , 0.1],[0.1 ,0.9]],
Ds: np.array = [[1, 0], [0.1, 0]],
alphas: np.array = [[1, 0], [1, 0]],
gamma_d = None,
epsilon_a = None,
L = None,
return_state_num = False,
init_state = None):
'''
Generates a dataset of 2D multi state trajectory with given parameters.
Parameters
----------
N : int
Number of trajectories
T : int
Length of the trajectory
M : list, array
Transition matrix between diffusive states
Ds : list
List of means and variances from which to sample the diffusion coefficient of each state. If element size is one, we consider variance = 0.
alphas : float
List of means and variances from which to sample the anomalous exponent of each state. If element size is one, we consider variance = 0.
gamma_d : list
Minimum factor between D of diffusive states (see ._sampling_diff_parameters)
epsilon_a : list
Distance between alpha of diffusive states (see ._sampling_diff_parameters)
L : float
Length of the box acting as the environment
deltaT : int, optional
Sampling time
return_state_num : bool
If True, returns as label the number assigned to the state at each time step.
init_state : bool
If True, the particle starts in state 0. If not, sample initial state.
Returns
-------
tuple
- trajs (array TxNx2): particles' position
- labels (array TxNx2): particles' labels (see ._multi_state for details on labels)
'''
# transform lists to numpy if needed
if isinstance(M, list):
M = np.array(M)
if isinstance(Ds, list):
Ds = np.array(Ds)
if isinstance(alphas, list):
alphas = np.array(alphas)
# Get epsilon and gamma
if gamma_d is None:
gamma_d = [1]*(M.shape[0]-1)
if epsilon_a is None:
epsilon_a = [0]*(M.shape[0]-1)
trajs = np.zeros((T, N, 2))
if return_state_num:
labels = np.zeros((T, N, 4))
else:
labels = np.zeros((T, N, 3))
for n in range(N):
### Sampling diffusion parameters for each state
alphas_traj = []
Ds_traj = []
alphas_traj, Ds_traj = self._sample_diff_parameters(alphas = alphas,
Ds = Ds,
num_states = M.shape[0],
epsilon_a = epsilon_a,
gamma_d = gamma_d)
#### Get trajectory from single traj function
traj, lab = self._multiple_state_traj(T = T,
L = L,
M = M,
alphas = alphas_traj,
Ds = Ds_traj,
return_state_num = return_state_num,
init_state = init_state
)
trajs[:, n, :] = traj
labels[:, n, :] = lab
return trajs, labels
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 61
class models_phenom(models_phenom):
@staticmethod
def _get_distance(x):
'''
Given a matrix of size Nx2, calculates the distance between the N particles.
Parameters
----------
x : array
Particles' positions
Returns
-------
array
Distance between particles
'''
M = np.reshape(np.repeat(x[ :, :], x.shape[0], axis = 0), (x.shape[0], x.shape[0], 2))
Mtrans = M.transpose(1,0,2)
distance = np.sqrt(np.square(M[:,:, 0]-Mtrans[:,:, 0])
+ np.square(M[:,:, 1]-Mtrans[:,:, 1]))
return distance
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 64
class models_phenom(models_phenom):
@staticmethod
def _make_escape(Pu, label, diff_state):
'''
Given an unbinding probablity (Pu), the current labeling of particles (label)
and the current state of particle (diff_state, either bound, 1, or unbound, 0), simulate an
stochastic binding mechanism.
Parameters
----------
Pu : float
Unbinding probablity
label : array
Current labeling of the particles (i.e. to which condensate they belong)
diff_state : array
Current state of the particles
Returns
-------
tuple
New labeling and diffusive state of the particles
'''
# if unbinding probability is zero
if Pu == 0:
return label, diff_state
label = label.copy()
diff_state = diff_state.copy()
label_dimers = np.unique(label[np.argwhere(diff_state == 1)])
for l in label_dimers:
if np.random.rand() < Pu:
# give new label to escaping particles
diff_state[label == l] = 0
label[label == l] = np.max(label)+np.arange(2)+1
return label, diff_state
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 67
class models_phenom(models_phenom):
@staticmethod
def _make_condensates(Pb, label, diff_state, r, distance, max_label):
'''
Given a binding probability Pb, the current label of particles (label),
their current diffusive state (diff_state), the particle size (r), their
distances (distance) and the label from which binding is not possible
(max_label), simulates a binding mechanism.
Parameters
----------
Pb : float
Binding probablity.
label : array
Current labeling of the particles (i.e. to which condensate they belong)
diff_state : array
Current state of the particles
r : float
Particle size.
distance : array
Distance between particles
max_label : int
Maximum label from which particles will not be considered for binding
Returns
-------
tuple
New labeling and diffusive state of the particles
'''
label = label.copy()
diff_state = diff_state.copy()
# Keeping track of the ones that will dimerize
already_dimer = []
for n, l in enumerate(label):
# Consider conditions in which particles do not dimerize
if n in already_dimer or diff_state[n] == 1 or l > max_label:
continue
# Extract distances to current particle
distance_to_current = distance[n,:]
distance_to_current[n] == 0
close_particles = np.argwhere((distance_to_current < 2*r) & (distance_to_current > 0)).flatten()
# Loop over all posible dimerizing candidates
for chosen in close_particles:
# Consider conditions in which particles do not dimerize
if chosen in already_dimer or diff_state[chosen] == 1 or label[chosen] > max_label:
continue
# Draw coin to see if particle dimerizes
if np.random.rand() < Pb:
# Add dimerized particles to the new dimer counter
already_dimer.append(chosen)
already_dimer.append(n)
# Update their diffusive state
diff_state[n] = 1
diff_state[chosen] = 1
# dimerize particles
label[chosen] = l
# if one particles dimers, not more clustering!
break
return label, diff_state
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 72
class models_phenom(models_phenom):
@staticmethod
def _stokes(D):
'''
Applies a Stokes-Einstein-like transformation to two diffusion coefficients.
Parameters
----------
D : tuple
Diffusion coefficients of the two binding particles.
Returns
-------
float
Resulting diffusion coefficient.
'''
D1 = D[0]; D2 = D[1]
return 1/((1/D1)+(1/D2))
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 75
class models_phenom(models_phenom):
def dimerization(self,
N = 10,
T = 200,
L = 100,
r = 1,
Pu = 0.1,
Pb = 0.01,
Ds: np.array = [[1, 0], [0.1, 0]],
alphas: np.array = [[1, 0], [1, 0]],
epsilon_a = 0, stokes = False,
return_state_num = False,
deltaT = 1
):
'''
Generates a dataset of 2D trajectories of particles perfoming stochastic dimerization.
Parameters
----------
N : int
Number of trajectories
T : int
Length of the trajectory
L : float
Length of the box acting as the environment
r : float
Radius of particles.
Pu : float in [0,1]
Unbinding probability.
Pb : float in [0,1])
Binding probability.
Ds : array
List of means and variances from which to sample the diffusion coefficient of each state. If element size is one, we consider variance = 0.
alphas : array
List of means and variances from which to sample the anomalous exponent of each state. If element size is one, we consider variance = 0.
epsilon_a : float
Distance between alpha of diffusive states (see ._sampling_diff_parameters)
stokes : bool
If True, applies a Stokes-Einstein like coefficient to calculate the diffusion coefficient of dimerized particles.
If False, we use as D resulting from the dimerization the D assigned to the dimerized state of one of the two particles.
deltaT : int
Sampling time
return_state_num : bool
If True, returns as label the number assigned to the state at each time step.
Returns
-------
tuple
- trajs (array TxNx2): particles' position
- labels (array TxNx2): particles' labels (see ._multi_state for details on labels)
'''
# transform lists to numpy if needed
if isinstance(Ds, list):
Ds = np.array(Ds)
if isinstance(alphas, list):
alphas = np.array(alphas)
# Info to save
pos = np.zeros((T, N, 2)) # position over time
label = np.zeros((T, N)).astype(int)
diff_state = np.zeros((T, N)).astype(int)
# Init position, labels
pos[0, :, :] = np.random.rand(N, 2)*L
label[0, :] = np.arange(pos.shape[1])
# Init alphas, Ds
# Calculate alpha/D for each particle in each state
alphas_N = np.array([gaussian(alphas[0], size = N, bound = self.bound_alpha),
gaussian(alphas[1], size = N, bound = self.bound_alpha)])
Ds_N = np.array([gaussian(Ds[0], size = N, bound = self.bound_D),
gaussian(Ds[1], size = N, bound = self.bound_D)])
# define labels over time by means of state 0
alphas_t = alphas_N[0,:].repeat(T).reshape(N,T).transpose()
Ds_t = Ds_N[0,:].repeat(T).reshape(N,T).transpose()
# initial displacements (all free particles)
disps = np.zeros((T, N, 2))
for n in range(N):
disps[:, n, 0] = models_phenom().disp_fbm(alphas_t[0, n], Ds_t[0, n], T, deltaT = deltaT)
disps[:, n, 1] = models_phenom().disp_fbm(alphas_t[0, n], Ds_t[0, n], T, deltaT = deltaT)
for t in (range(1, T)):
# Find max label to account later for escaped
max_label = np.max(label[t-1, :])
# Make particles escape
label[t, :], diff_state[t, :] = self._make_escape(Pu,
label[t-1, :],
diff_state[t-1, :])
lab, diff = label[t, :].copy(), diff_state[t, :].copy()
# get distance + increasing it for escaped to avoid reclustering
distance = self._get_distance(pos[t-1, :, :])
# Merge particles in condensates
label[t, :], diff_state[t, :] = self._make_condensates(Pb,
label[t, :],
diff_state[t, :],
r, distance, max_label)
# Find particles which changed state
label_changed, counts = np.unique(label[t, np.not_equal(diff_state[t-1,:], diff_state[t,:])],
return_counts = True)
# Calculate new displacements for particles which changed state
for l, count in zip(label_changed, counts):
index = int(np.argwhere(label[t,:] == l)[0])
state = diff_state[t, index]
### Calculating new diffusion parameters
# anomalous exponent
if epsilon_a != 0 and state == 1:
new_alpha = gaussian(alphas[1], size = 1, bound = self.bound_alpha)
idx_while = 0
while models_phenom()._constraint_alpha(alphas_N[0, label[t, :] == l].min(), new_alpha, epsilon_a):
new_alpha = gaussian(alphas[1], size = 1, bound = self.bound_alpha)
idx_while += 1
if idx_while > 100: # check that we are not stuck forever in the while loop
raise FileNotFoundError(f'Could not find correct alpha in 100 steps. State distributions probably too close.')
alphas_t[t:, label[t, :] == l] = new_alpha
else:
# if no epsilon is given, use the alpha of the first particle
# While here it seems we take both, in the for loop where we assign the displacements below we only
# sample with the first value.
alphas_t[t:, label[t, :] == l] = alphas_N[state, label[t, :] == l].repeat(T-t).reshape(count, T-t).transpose()
# diffusion coefficient
if stokes and state == 1:
Ds_t[t:, label[t, :] == l] = models_phenom()._stokes(Ds_t[t-1, label[t, :] == l])
else: # if no stokes is given, use the D assgined to the dimerized state of the first particle
Ds_t[t:, label[t, :] == l] = Ds_N[state, label[t, :] == l].repeat(T-t).reshape(count, T-t).transpose()
for idx, i in enumerate(np.argwhere(label[t,:] == l)):
# We first calculate the displacements so dimers have same motion
if idx == 0:
if T-t > 1:
disp_current_x = models_phenom().disp_fbm(float(alphas_t[t, i]), float(Ds_t[t, i]), T-t, deltaT = deltaT).reshape(T-t, 1)
disp_current_y = models_phenom().disp_fbm(float(alphas_t[t, i]), float(Ds_t[t, i]), T-t, deltaT = deltaT).reshape(T-t, 1)
else:
disp_current_x = np.sqrt(2*float(Ds_t[t, i])*deltaT)*np.random.randn(1)
disp_current_y = np.sqrt(2*float(Ds_t[t, i])*deltaT)*np.random.randn(1)
disps[t:, i, 0] = disp_current_x
disps[t:, i, 1] = disp_current_y
# Update position
pos[t, :, :] = pos[t-1,:,:]+disps[t, :, :]
# Consider boundary conditions
if L is not None:
while np.max(pos[t,:, :])>L or np.min(pos[t,:, :])< 0:
pos[t, pos[t,:, :] > L] = pos[t, pos[t,:, :] > L] - 2*(pos[t, pos[t,:, :] > L] - L)
pos[t, pos[t,:, :] < 0] = - pos[t, pos[t,:, :] < 0]
# Define state of particles based on values of alphas: either free or directed
label_diff_state = np.zeros_like(alphas_t)
label_diff_state[alphas_t < self.alpha_directed] = self.lab_state.index('f')
label_diff_state[alphas_t >= self.alpha_directed] = self.lab_state.index('d')
if return_state_num:
return pos, np.array((alphas_t,
Ds_t,
label_diff_state,
diff_state)).transpose(1,2,0)
else:
return pos, np.array((alphas_t,
Ds_t,
label_diff_state
)).transpose(1,2,0)
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 81
class models_phenom(models_phenom):
@staticmethod
def _update_bound(mask, # Current binding array
N, # Number of particles
pos, # Position of particles
Nt, # Number of traps
traps_pos, # Position of traps
Pb, # Binding probability
Pu, # Unbinding probability
r, # Trap radius
): # Updated binding array
'''
Binds and unbinds particles to traps based on their position and binding and unbinding probabilities
Parameters
----------
mask : array
Current binding array
N : int
Number of particles
pos : array
Position of particles
Nt : int
Number of traps
traps_pos : array
Position of traps
Pb : float in [0,1]
Binding probability
Pu : float in [0,1]
Unbinding probability
r : float
Trap radius
Returns
-------
array
Updated binding array
'''
# from the ones that are bound, get the ones that unbind. These will be descarted for binding in same time step
mask_new_free = np.array(1-(np.random.rand(N) < Pu)*mask).astype(bool)
# calculate the distance between traps and particles
d = models_phenom._get_distance(np.vstack((traps_pos, pos)))[Nt:, :Nt]
mask_close = (d < r).sum(1).astype(bool)
# get mask for binding
mask_new_bind = np.random.rand(N) < Pb
# update the bound vector with the previous conditions:
# first, the ones that unbind
mask *= mask_new_free
# then, the ones that are close + bind. Mask_new_free is added to avoid binding
# of the ones that just unbound
mask += mask_close*mask_new_bind*mask_new_free
return mask
# %% ../source_nbs/lib_nbs/models_phenom.ipynb 83
class models_phenom(models_phenom):
def immobile_traps(self,
N = 10,
T = 200,
L = 100,
r = 1,
Pu = 0.1,
Pb = 0.01,
Ds = [1, 0],
alphas = [1, 0],
Nt = 10,
traps_pos: np.array = None,
deltaT = 1
):
'''
Generates a dataset of 2D trajectories of particles diffusing in an environment with immobilizing traps.
Parameters
----------
N : int
Number of trajectories
T : int
Length of the trajectory
L : float
Length of the box acting as the environment
r : float
Radius of particles.
Pu : float in [0,1]
Unbinding probability.
Pb : float in [0,1])
Binding probability.
Ds : list, float
Mean and variance from which to sample the diffusion coefficient of the free state. If float, we consider variance = 0
alphas : list, float
Mean and variance from which to sample the anomalous exponent of the free state. If float, we consider variance = 0
Nt : int
Number of traps
traps_pos : array, None
Positions of the traps. Can be given by array or sampled randomly if None.
deltaT : int
Sampling time.
Returns
-------
tuple
- trajs (array TxNx2): particles' position
- labels (array TxNx2): particles' labels (see ._multi_state for details on labels)
'''
# Info to output
pos = np.zeros((T, N, 2)) # position over time
output_label = np.zeros((T, N, 3))
disps = np.zeros((T, N, 2))
diff_state = np.zeros((T, N)).astype(int)
mask_bound = diff_state[0, :].astype(bool)
# Init position, labels
pos[0, :, :] = np.random.rand(N, 2)*L
# Init alphas, Ds
# Calculate alpha/D for each particle in state free state
alphas_N = gaussian(alphas, size = N, bound = self.bound_alpha)
Ds_N = gaussian(Ds, size = N, bound = self.bound_D)