-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_bs.py
More file actions
executable file
·2048 lines (1667 loc) · 82.7 KB
/
Copy pathintegration_bs.py
File metadata and controls
executable file
·2048 lines (1667 loc) · 82.7 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
#! /bin/sh
""":"
exec ipython -i $0 ${1+"$@"}
"""
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import flow_load as fll
import matplotlib.cm as cm
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from scipy.signal import argrelextrema,argrelmin,argrelmax
from scipy.optimize import brentq
from scipy.optimize import brenth
from scipy.optimize import newton
from scipy import signal as scisignal # module to interpolate signal
from scipy import stats
import seaborn as sns
import latticediff as lat
import random
import os,sys
import datetime
import json
import copy
import yol_colors as yolcol
import pandas as pd
import matplotlib.gridspec as gridspec
import fitpars as fp
import cv2
#import line_profiler
sbcolorcycle=sns.color_palette("Set1",n_colors=9,desat=0.8) # Setting Colour palette
sns.set_palette("Set1",n_colors=9,desat=0.8)
#sbcolorcycle=sns.color_palette("deep") # Setting Colour palettes
sbcolorcyclebright=sns.color_palette("bright")
sbcolorcycledark=sns.color_palette("dark")
sbcolorcyclemuted=sns.color_palette("muted")
clw = 2.0 # circle line width (also for ellipse)
talpha = 0.05 # alpha for trajectory
sns.set_style("ticks") # Set plot properties
sns.set_context("talk")
sns.despine()
newblack = sns.xkcd_rgb["charcoal"]
eps = 1E-80
eps2 = 1E-8
colorcycle=sbcolorcycle
def facet_scatter(x,y,c, **kwargs):
"""Draw scatterplot with point colors from a faceted DataFrame columns."""
kwargs.pop("color")
plt.scatter(x,y,c=c, **kwargs)
# Create the color palettes used in the manuscript #####################################################
plt.register_cmap(name='RedtoGreen', data=yolcol.cdict_RedtoGreen)
plt.register_cmap(name='AlphatoBlue', data=yolcol.cdict_AlphatoBlue)
###### Dictionary with the integration parameters
integdict = {'dt':0.1,'totaltime':1000}
##### Class with the parameters of the model
# Numbers used are not significant
class param():
alpha_X = 15.25
alpha_Y = 140.0
delta_X = 1.0
delta_Y = 1.0
beta_X = 1.0
beta_Y = 1.0
K_IPTG = 0.295
K_AHL = 4.05
K_LACI = 0.295
K_TETR = 1.0
K_ATC = 1.0
n_LACI = 2.47
n_AHL = 2.08
n_TETR = 2.0
# Global dictionaries and lists to call the parameters
orderedpars = {"alpha_X":0, "alpha_Y":1, "beta_X":2, "beta_Y":3,
"K_IPTG":4, "K_AHL":5
, "K_LACI":6, "K_TETR":7,
"K_ATC":8, "n_LACI":9, "n_AHL":10,
"n_TETR":11,"delta_X":12,"delta_Y":13}
parnames = ['$\\alpha_X$','$\\alpha_Y$','$\\beta_X$', '$\\beta_Y$',
'$K_{IPTG}$','$K_{AHL}$','$K_{LACI}$',
'$K_{TETR}$','$K_{ATC}$',
'$n_{LACI}$','$n_{AHL}$','$n_{TETR}$' ]
par = param() # global instance of the class. New local instances can be created if necessary
#### Class with the chemical concentrations
class chem():
IPTG = 0.0
AHL = 0.0
ATC = 0.0
ch = chem() # global instance of the class. New local instances can be created if necessary
##############################################################################
#//////////////////////////// DYNAMICAL SYSTEM DEFINITION /////////////////////////////////
#################################################################################
def flow(X,Y,chh = ch, parr = par):
''' returng the value for xdot and ydot for a given set of parameters par
and a given set of inducers ch.
'''
# X is expression of the lux - lac promoter encoding TetR and mCherry
# Y is expression of the tet promote inducing encoding LacI and GFP
# X and Y are measurments of fluorescence, to use them I am goind to substract some background
# to transform it to concentrations
X = np.maximum(X - parr.alpha_X,0) # removing fluorescence background on X
Y = np.maximum(Y - parr.alpha_Y,0) # removing fluorescence background on Y
# X = X - parr.alpha_X
# Y = Y - parr.alpha_Y
# note the danger of this expression, values of X should not let drop below X to have analytical significance
# nevertheless this has meaning (fluorescences below the background correspond to background -> X=0), in addition
# it can help to have a proper analysis when X- parr.alpha_X goes a bit below zero (due to computational error) and
# we don't want this to affect the analysis
# the role of AHL is an AND gate coded as a Hill activator
flow_X = np.power(chh.AHL * parr.K_AHL,parr.n_AHL)/(1 + np.power(chh.AHL*parr.K_AHL,parr.n_AHL))
# LacI can be available to bind to the lux - lac promoter if they do not form a complex with IPTG molecules
free_LacI = Y/(parr.K_IPTG * chh.IPTG + 1)
# free LacI acts as an AND repressor by looping the DNA coded as a Hill function
flow_X = flow_X / (1 + np.power(parr.K_LACI * free_LacI, parr.n_LACI))
flow_X = parr.beta_X*flow_X # Note that I am introducing handwavily some leakiness of the promoter (any better way?)
flow_X = flow_X - parr.delta_X * X # degradation of protein X (mCherry and TetR are considered the same...)
# free TeTR can inhibit the expression of the TetO upstream the gene Y
# aTc can attach to TetR inhibiting the binding, I am going to assume normal binding kinetics
free_TetR = X/(parr.K_ATC * chh.ATC + 1)
# For the repression from the free_TetR I will assume Hill function
flow_Y = 1.0 / (1 + np.power(parr.K_TETR * free_TetR, parr.n_TETR))
flow_Y = parr.beta_Y*flow_Y # Note that I am introducing handwavily some leakiness of the promoter (any better way?)
flow_Y = flow_Y - parr.delta_Y * Y
# note that the flows do not need to be transformed to fluorescence (without background)
# since they coincide in both cases
return flow_X,flow_Y
def getJacobian(X,Y,chh = ch, parr = par):
''' Returns Jacobian of the flow
'''
Jacobian = np.zeros([2,2])
X = np.maximum(X - parr.alpha_X,0) # fluorescence background on X
Y = np.maximum(Y - parr.alpha_Y,0) # fluorescence background on X
free_LacI = Y/(parr.K_IPTG * chh.IPTG + 1)
free_TetR = X/(parr.K_ATC * chh.ATC + 1)
Jacobian[0,0] = -parr.delta_X # Diagonals of the Jacobian corresponds with the degradation rates
Jacobian[1,1] = -parr.delta_Y
Jacobian[0,1] = -np.power(chh.AHL * parr.K_AHL,parr.n_AHL)/(1 + np.power(chh.AHL*parr.K_AHL,parr.n_AHL))
Jacobian[0,1] /= (1 + np.power(parr.K_LACI * free_LacI, parr.n_LACI))
Jacobian[0,1] /= (1 + np.power(parr.K_LACI * free_LacI, parr.n_LACI))
Jacobian[0,1] *= parr.K_LACI * parr.n_LACI * np.power(parr.K_LACI * free_LacI, parr.n_LACI-1)
Jacobian[0,1] *= parr.beta_X
Jacobian[0,1] /= (parr.K_IPTG * chh.IPTG + 1)
Jacobian[1,0] = -parr.beta_Y / (1 + np.power(parr.K_TETR * free_TetR, parr.n_TETR))
Jacobian[1,0] /= (1 + np.power(parr.K_TETR * free_TetR, parr.n_TETR))
Jacobian[1,0] *= parr.n_TETR * parr.K_TETR * np.power(parr.K_TETR * free_TetR, parr.n_TETR-1)
Jacobian[1,0] /= (parr.K_ATC * chh.ATC + 1)
return Jacobian
def flowWithNoiseIntensity(X,Y,chh = ch, parr = par):
# assuming that the amount of morphogen molecules is larger compared to the proteins interacting proteins
# and that the change in protein number is low enough to consider it constant in a timestep
# joining the whole production to noise to a single gaussian then we can apply CLE as
# X and Y are measurments of fluorescence, to use them I am going to substract some background
# to transform it to concentrations
X = np.maximum(X - parr.alpha_X,0) # fluorescence background on X
Y = np.maximum(Y - parr.alpha_Y,0) # fluorescence background on X
# X = X - parr.alpha_X
# Y = Y - parr.alpha_Y
# note the danger of this expression, values of X should not let drop below X to have analytical significance
# nevertheless this has meaning (fluorescences below the background correspond to background -> X=0), in addition
# it can help to have a proper analysis when X- parr.alpha_X goes a bit below zero (due to computational error) and
# we don't wnat this to affect the analysis
# the role of AHL is an AND gate coded as a Hill activator
flow_X = np.power(chh.AHL * parr.K_AHL,parr.n_AHL)/(1 + np.power(chh.AHL*parr.K_AHL,parr.n_AHL))
# LacI can be available to bind to the lux - lac promoter if they do not form a complex with IPTG molecules
free_LacI = Y/(parr.K_IPTG * chh.IPTG + 1)
# free LacI acts as an AND repressor by looping the DNA coded as a Hill function
flow_X = flow_X / (1 + np.power(parr.K_LACI * free_LacI, parr.n_LACI))
flow_X = parr.beta_X*flow_X # Note that I am introducing handwavily some leakiness of the promoter (any better way?)
noise_X = np.sqrt(flow_X*flow_X + parr.delta_X * X * parr.delta_X * X) # CLE assuming stoichiometry 1
# noise_X = parr.delta_X * (X+parr.alpha_X) # CLE assuming stoichiometry 1
flow_X = flow_X - parr.delta_X * X # degradation of protein X (mCherry and TetR are considered the same...)
# free TeTR can inhibit the expression of the TetO upstream the gene Y
# aTc can attach to TetR inhibiting the binding, I am going to assume normal binding kinetics
free_TetR = X/(parr.K_ATC * chh.ATC + 1)
# For the repression from the free_TetR I will assume Hill function
flow_Y = 1.0 / (1 + np.power(parr.K_TETR * free_TetR, parr.n_TETR))
flow_Y = parr.beta_Y*flow_Y # Note that I am introducing handwavily some leakiness of the promoter (any better way?)
noise_Y = np.sqrt(flow_Y*flow_Y + parr.delta_Y * Y * parr.delta_Y * Y) # CLE assuming stoichiometry 1
# noise_Y = parr.delta_Y * (Y+parr.alpha_Y) # CLE assuming stoichiometry 1
flow_Y = flow_Y - parr.delta_Y * Y
# note that the flows do not need to be transformed to fluorescence (without background)
# since they coincide in both cases
return flow_X,flow_Y,noise_X,noise_Y
#
# Flow of Gardner et al Nature:
# flow_X = parr.alpha_X/(1+np.power(Y,parr.n_X)) - parr.delta_X * X
# flow_Y = parr.alpha_Y/(1+X/np.power(1+chh.IPTG/parr.K_IPTG,parr.n_IPTG)) - parr.delta_Y * Y
#
# with parameters:
# alpha_X = 156.25
# alpha_Y = 15.6
# delta_X = 1.0
# delta_Y = 1.0
# K_IPTG = 2.9618E-5
# n_IPTG = 2.0015
# n_X = 2.5
###############################################################################
##### INTEGRATION OF THE DYNAMICAL SYSTEM
##############################################################################
#/////////////////////////////////////////////////////////////////////////
def integration(totaltime = None, dt = None,initcond=[0,0], result = "traj", stochastic = False, volume = 100, parr = par, chh = ch):
''' Euler integration of a trajectory for an initial set of coordinates initcond
result --- 'traj' returns the whole trajectory, otherwise only the last point is returned
'''
#Integration of the trajectory. Returns a vector of X,Y,Z,t
#
ti=0 # Initial time
if not dt :
dt = integdict["dt"]
if not totaltime:
totaltime = integdict["totaltime"]
sdt = np.sqrt(dt)
volume_prefactor = np.sqrt(1.0/volume)
Xi,Yi=initcond
if result =="traj":
X=[] # vector containing trajectory
Y=[]
t=[]
while (ti<totaltime):
if result == "traj":
X.append(Xi)
Y.append(Yi)
t.append(ti)
if stochastic:
flow_X,flow_Y,noise_X,noise_Y = flowWithNoiseIntensity(Xi,Yi,chh,parr)
Xi = Xi + dt*flow_X + noise_X*sdt*volume_prefactor * np.random.normal()
Yi = Yi + dt*flow_Y + noise_Y*sdt*volume_prefactor * np.random.normal()
else:
flow_X,flow_Y = flow(Xi,Yi,chh,parr)
Xi = Xi+dt*flow_X
Yi = Yi+dt*flow_Y
ti = ti + dt
if result == "traj":
return X,Y,t
else:
return Xi,Yi,ti
#//////////////////////////////////////////////////////////////////////
### LINEAR STABILITY ANALYSIS AND COMPARISON WITH EXPERIMENTAL DATA
#/////////////////////////////////////////////////////////////////////////
def steady_states(X0 = -8, XF = 4, NX = 100, parr = par, chh = ch, givenxi = None):
'''Compute the steady states available for the bistable switch along X = [10^X0,10^XF]
this range is divided in NX points and the extrema of f(X)-X are located.
Between each extrema, if there is a change of sign of the flow, it means that
there is a steady state between these points that is refined by the Brent routine
If givenxi is different than None, then the list of initial X is given by givenxi
returns a list of steady states with their coordinates X,Y,
their stability and the eigenvalues of the Jacobian at that point
'''
ss = [] # list of found steady states
if givenxi is None:
xi = np.logspace(X0,XF,num=NX)
else:
xi = givenxi
yi = flow(xi,parr.alpha_Y,parr = parr, chh = chh)[1]/parr.delta_Y+parr.alpha_Y
zi = flow(xi,yi,parr = parr,chh = chh)[0] # this is zero at the steady state xstar,
# so zi computes the deviation from the steady state
maxi=argrelmax(np.array(zi))[0] # look for the relative maxima
mini=argrelmin(np.array(zi))[0] # and minima on x
zcpos=np.concatenate(([0],maxi,mini,[NX-1]))
zcpos=np.sort(zcpos) # zcpos contains the regions that alocate steady states
idx=0
while(idx<(len(zcpos)-1)):
if ((zi[zcpos[idx]]*zi[zcpos[idx+1]])<0):
# if there is a change of sign, a brentq algorithm is used to find the zero (steady-state) xstar
xstar = brenth(lambda x: flow(x,flow(x,parr.alpha_Y,parr = parr, chh = chh)[1]/par.delta_Y+parr.alpha_Y,parr = parr, chh = chh)[0] ,xi[zcpos[idx]],xi[zcpos[idx+1]])
# we are using the brenth algorithm because the hyperbolic finds faster minima in this case (tested numerically)
ystar = flow(xstar,parr.alpha_Y,parr = parr, chh = chh)[1]/parr.delta_Y+parr.alpha_Y
stable,ls=stabilityJacobian(xstar,ystar,parr = parr, chh = chh) # stability is assessed by diagonalization of the Jacobian
if stable == True:
stable = 'stable'
elif stable == False:
stable = 'unstable'
ss.append({"X":xstar,"Y":ystar,"stab":stable,"lambdas":ls})
idx=idx+1
borders = [0,-1] # possibility that the zero is at the edge of the vector
for b in borders:
if abs(zi[b]) < eps2 :
xstar = xi[b]
ystar = yi[b]
stable,ls=stabilityJacobian(xstar,ystar,parr = parr, chh = chh)
if stable == True:
stable = 'stable'
elif stable == False:
stable = 'unstable'
ss.append({"X":xstar,"Y":ystar,"stab":stable,"lambdas":ls})
return ss
def loglikelihood(dataset, paramvector):
''' Calculate the loglikelihood of the dataset given a vector of parameters
'''
# Casting from list (useful for the use of PyDream) to the global parameter structure par
par.alpha_X = paramvector[orderedpars['alpha_X']]
par.alpha_Y = paramvector[orderedpars['alpha_Y']]
par.beta_X = paramvector[orderedpars['beta_X']]
par.beta_Y = paramvector[orderedpars['beta_Y']]
par.K_IPTG = paramvector[orderedpars['K_IPTG']]
par.K_AHL = paramvector[orderedpars['K_AHL']]
par.K_LACI = paramvector[orderedpars['K_LACI']]
par.K_TETR = paramvector[orderedpars['K_TETR']]
par.K_ATC = paramvector[orderedpars['K_ATC']]
par.n_LACI = paramvector[orderedpars['n_LACI']]
par.n_AHL = paramvector[orderedpars['n_AHL']]
par.n_TETR = paramvector[orderedpars['n_TETR']]
#par.delta_X = paramvector[orderedpars['delta_X']]
#par.delta_Y = paramvector[orderedpars['delta_Y']]
par.delta_X = 1.0
par.delta_Y = 1.0
totalloglklh = 0
# vector to look for values
xii = np.logspace(np.log10(par.alpha_X+eps),np.log10(par.alpha_X+par.beta_X-eps),num=1000)
for irow,row in dataset.iterrows():
# for each point in the dataset set the inducer concentration
chem.AHL = row['AHL']
chem.IPTG = row['IPTG']
chem.aTc = row['aTc']
# search of steady states is limited to the range of possible values of fluorescence X
ss = steady_states(np.log10(par.alpha_X+eps),np.log10(par.alpha_X+par.beta_X-eps),1000,parr = par, chh = chem, givenxi = xii)
maxlklh = -1E10 # basal loglikelihood, to avoid outlayers
steadyStatesCount = 0
if ss == []:
print("Missed point!!", chem.AHL , chem.IPTG, chem.aTc)
for state in ss:
if state['stab'] == 'stable':
steadyStatesCount += 1
# normalizations of Gaussians might be dropped to give the same relevance to heights of coexistent peaks
# of difference basins of attractions i.e. that a narrow peak in coexistence with a broad one does not want to
# absorb everything
lklh = ((state['X']-row['RED_median_normed'])/(row['RED_std']))**2 # assuming gaussian
lklh += ((state['Y']-row['GREEN_median_normed'])/(row['GREEN_std']))**2 # assuming gaussian
# Alternative Likelihoods
#lklh = ((state['X']-row['RED_median_normed'])/1000.0)**2 # assuming gaussian
#lklh += ((state['Y']-row['GREEN_median_normed'])/1000.0)**2 # assuming gaussian
# Adding normalizations...
#lklh = lklh + np.log(row['GREEN_std']*np.sqrt(2.0*np.pi)) # normalization of gaussian
#lklh = lklh + np.log(row['RED_std']*np.sqrt(2.0*np.pi)) # normalization of gaussian
lklh = lklh*(-1.0)
if lklh > maxlklh:
maxlklh = lklh
if ((steadyStatesCount>1) and (row['multistability'] ==1) or
(steadyStatesCount==1) and (row['multistability'] ==2)):
maxlklh -= 100 # penalizing not finding the right number of steady states
# print chem.AHL, chem.IPTG, row['Red'], row['Green'], ss, mindistance
totalloglklh += maxlklh
print("vector: ", paramvector)
# print("logvector: ", np.log10(paramvector))
print("log likelihood: ", totalloglklh)
return totalloglklh
def getbifurcationcurves_AHL(limAHL = [0.001,100], npoints = 1000, IPTG=0, ATC=0):
''' Return the bifurcation curves in a range of AHL by filling the three curves
curve_stable1, curbe_stable2, and curve_unstable.
Each curve is a list of AHL values and the corresponding position X,Y
'''
print()
AHLarray = np.logspace(np.log10(limAHL[0]), np.log10(limAHL[1]), npoints)
print(AHLarray)
ch.ATC = ATC
ch.IPTG = IPTG
curve_stable_1 = np.ones((0,2))
curve_unstable = np.ones((0,2))
curve_stable_2 = np.ones((0,2))
last_value_1 = 0 # This values will be used to choose curve to continue
last_value_2 = np.inf
for AHLv in AHLarray:
# print('AHLv',AHLv)
ch.AHL = AHLv
ss = steady_states(np.log10(par.alpha_X+eps),np.log10(par.alpha_X+par.beta_X-eps),
NX = 1000, parr = par, chh = ch, zerocorrection = True, givenxi = None)
sss = [] # list of stable steady states found for this value of AHL
for xss in ss:
if xss['stab']=='stable':
sss.append(xss['X'])
# not assigned until we know all of them
else: # unstable
curve_unstable = np.vstack((curve_unstable,[AHLv,xss['X']]))
if len(sss)==1: # Only one state then we decide which branch the it belongs to
if (abs(sss[0]-last_value_1) < abs(sss[0]-last_value_2)):
last_value_1 = sss[0]
curve_stable_1 = np.vstack((curve_stable_1,[AHLv,sss[0]]))
last_value_2 = np.inf
else:
last_value_2 = sss[0]
curve_stable_2 = np.vstack((curve_stable_2,[AHLv,sss[0]]))
last_value_1 = np.inf
elif len(sss)==2: # bistable regime
if (abs(sss[0]-last_value_1) < abs(sss[0]-last_value_2)):
l1 = 0
l2 = 1
else:
l1 = 1
l2 = 0
last_value_1 = sss[l1]
last_value_2 = sss[l2]
curve_stable_1 = np.vstack((curve_stable_1,[AHLv,sss[l1]]))
curve_stable_2 = np.vstack((curve_stable_2,[AHLv,sss[l2]]))
else:
print("Error, too many stable states")
return curve_stable_1,curve_stable_2,curve_unstable
##################
# /////////////// AUXULIARY LINEAR STABILITY FUNCTIONS ////////////////////////////////////////////////////
##################
def stabilityJacobian(x,y,eps = 1E-10,parr = par, chh = ch):
''' Compute numerically the stability of a steady state
diagonalizing the numerical Jacobian
'''
fxx,fyx = flow(x+eps,y,parr = parr,chh = chh)
fxy,fyy = flow(x,y+eps,parr = parr,chh = chh)
lambdas,vecs=np.linalg.eig([[fxx,fyx],[fxy,fyy]])
stable=all([l.real<0 for l in lambdas])
return stable, lambdas
def getNumericalJacobian(x,y,eps = 1E-10,parr = par, chh = ch):
''' Compute the Jacobian numerically at a point buy using finite differences
'''
print("Jac",x,y,eps,x+eps)
fxxP,fyxP = flow(x+eps,y,parr = parr,chh = chh)
fxxM,fyxM = flow(x-eps,y,parr = parr,chh = chh)
fxyP,fyyP = flow(x,y+eps,parr = parr,chh = chh)
fxyM,fyyM = flow(x,y-eps,parr = parr,chh = chh)
fxx = (fxxP-fxxM)/(2*eps)
fyy = (fyyP-fyyM)/(2*eps)
fxy = (fxyP-fxyM)/(2*eps)
fyx = (fyxP-fyxM)/(2*eps)
return np.array([[fxx,fyx],[fxy,fyy]])
#####################################################################
# #////////////////////////////////// PLOTS ////////////////////////
######################################################################
# Plots used to show stability and integration of the flow equations without spatial diffusion of signals
def plotpargrid(chain = 'all', ordermethod = 'logps', condition = 40000, figsize = 20):
'''
Plot a grid with the results of the MCMC
chain --- which chains to use. 'all' uses all the chains
ordermethod --- There are two different ways of ordering the goodness of the results.
One of them is compute one by one the likelihoods for each parset
This methods can be quite slow sometimes. The second option is to load the logps from the output of pyDream
condition --- Which output file to read (condition refers to number of samples from the MCMC)
figsize --- size of figure in inches
'''
ntrim = 10000 # trim the transient of the MCMC
stride = 50 # ignore every 50 points to avoid close points and make the plot lighter
condition = str(condition)
chain = chain
lklh_ci = 0.9 ## confidence interval threshold to plot
data1 = np.array([]).reshape(0,len(parnames))
lklh_list = np.array([])
if chain == 'all':
chainlist = [0,1,2]
else:
chainlist = [chain]
for ch in chainlist:
data1_temp = np.load('dream/bsfit_sampled_params_chain'+str(ch)+'_'+condition+'.npy')
logpsdata1_temp = np.load('dream/bsfit_logps_chain'+str(ch)+'_'+condition+'.npy')
lklh_list_temp = np.array([l[0] for l in logpsdata1_temp])
data1_temp = data1_temp[ntrim::stride]
lklh_list_temp = lklh_list_temp[ntrim::stride]
data1 = np.vstack((data1,data1_temp))
lklh_list = np.concatenate((lklh_list,lklh_list_temp))
# Trim data with best likelihoods
if ordermethod == 'logps':
sorted_idxs = lklh_list.argsort()
data1_sorted = data1[sorted_idxs]
lklh_list_sorted = lklh_list[sorted_idxs]
bestlklh = lklh_list[-1]
worstlklh = lklh_list[0]
bestpars = data1_sorted[-1]
ibestlklh = -1
# threshold_lklh = lklh_list_sorted[int(len(lklh_list_sorted)*lklh_ci)] # finding the lklh at a certain confidence interval
print("ibestlklh: ", ibestlklh)
print("bestlklh: ", bestlklh)
print("bestpars:", bestpars)
# print "teopars:", teopars
print("worstlklh: ", worstlklh)
# print "thresholdlklh: ", threshold_lklh
print(data1_sorted)
axislim = np.array([fp.lower_limits,fp.lower_limits+fp.scale_limits]).T
axislim[-1] = 10**axislim[-1]
axislim[-2] = 10**axislim[-2]
axislim[-3] = 10**axislim[-3]
axislim[0] = [0,550]
axislim[1] = [0,550]
# plot_parnames = ['log($\\alpha_X$)','log($\\alpha_Y$)','log($\\beta_X$)',
# 'log($\\beta_Y$)','log($K_{IPTG}$)','log($K_{AHL}$)',
# 'log($K_{LACI}$)','log($K_{TETR}$)','log($K_{ATC}$)',
# '$n_{LACI}$','$n_{AHL}$','$n_{TETR}$']
# Plot parnames excluding KaTc
plot_parnames = ['$\\alpha_X$','$\\alpha_Y$','$\\mathrm{log}_{10}\\tilde{\\beta}_X$',
'$\\mathrm{log}_{10}\\tilde{\\beta}_Y$','$\\mathrm{log}_{10}K_{IPTG}$','$\\mathrm{log}_{10}K_{AHL}$',
'$\\mathrm{log}_{10}K_{LACI}$','$\\mathrm{log}_{10}K_{TETR}$',
'$n_{LACI}$','$n_{AHL}$','$n_{TETR}$']
data1_sorted = np.delete(data1_sorted,8,1) # deleting column for KATC
axislim = np.delete(axislim,8,0) # deleting column for KATC
data_df1 = pd.DataFrame(data = data1_sorted, columns = plot_parnames)
data_df1['$\\alpha_X$'] = 10**data_df1['$\\alpha_X$']
data_df1['$\\alpha_Y$'] = 10**data_df1['$\\alpha_Y$']
data_df1['$n_{LACI}$'] = 10**data_df1['$n_{LACI}$']
data_df1['$n_{AHL}$'] = 10**data_df1['$n_{AHL}$']
data_df1['$n_{TETR}$'] = 10**data_df1['$n_{TETR}$']
print("Array dimesions: ", data_df1.shape)
cmap = cm.get_cmap('viridis')
fig = plt.figure(figsize = (figsize,figsize))
gs = gridspec.GridSpec(len(plot_parnames), len(plot_parnames))
gaxes = []
# Plot each subplot in coordinates irow,icol in a grid of plots
for irow,row in enumerate(plot_parnames):
grow = []
for icol,col in enumerate(plot_parnames):
grow.append(plt.subplot(gs[irow,icol]))
gaxes.append(grow)
# Plot of offdiagonal scatter plots
for irow,rowname in enumerate(plot_parnames):
for icol,colname in enumerate(plot_parnames):
## scatter plots
if icol != irow:
gaxes[irow][icol].set_facecolor(cmap(0))
gaxes[irow][icol].scatter(data_df1[colname],data_df1[rowname], c = lklh_list_sorted,
s = 2, cmap = 'viridis', vmin = lklh_list_sorted[0], vmax = lklh_list_sorted[-1])
gaxes[irow][icol].set_xlim([axislim[icol][0],axislim[icol][1]])
gaxes[irow][icol].set_ylim([axislim[irow][0],axislim[irow][1]])
## density plots
if icol == irow:
gaxes[irow][icol].hist(data_df1[rowname],histtype = 'stepfilled', color = sbcolorcyclemuted[4], edgecolor = sbcolorcycledark[4])
gaxes[irow][icol].set_xlim([axislim[irow][0],axislim[irow][1]])
if irow==(len(plot_parnames)-1): # bottom row
gaxes[irow][icol].set_xlabel(colname)
else: # not bottom row
gaxes[irow][icol].tick_params(labelbottom=False)
if icol==0: # leftmost column
gaxes[irow][icol].set_ylabel(rowname)
else:
gaxes[irow][icol].tick_params(labelleft=False)
if (irow==0 and icol==0): # top left panel fix label
gaxes[irow][icol].tick_params(labelleft=False)
gaxes[irow][icol].yaxis.set_label_coords(-0.5,0.5)
plt.gcf().set_size_inches(figsize, figsize)
plt.savefig('pargrid_'+str(chain)+'_hill_'+str(ordermethod)+'.png',dpi=300)
plt.show()
###############################################################################
def plot_testpars(chain = 1, parset = 'fit', figsize = (10,10), condition = 40000, bifurcation_line = False):
'''
Plot the bifurcation diagram on top of the input experimental data used to fit the model
'''
if parset == 'fit':
condition = str(condition)
chain = chain
data1 = np.load('dream/bsfit_sampled_params_chain'+str(chain)+'_'+condition+'.npy')
logpsdata1 = np.load('dream/bsfit_logps_chain'+str(chain)+'_'+condition+'.npy')
lklh_list = np.array([l[0] for l in logpsdata1])
sorted_idxs = lklh_list.argsort()
data1_sorted = data1[sorted_idxs]
bestpars = data1_sorted[-1]
print(bestpars)
#ibestlklh = -1
par.alpha_X = 10**bestpars[orderedpars['alpha_X']]
par.alpha_Y = 10**bestpars[orderedpars['alpha_Y']]
par.beta_X = 10**bestpars[orderedpars['beta_X']]
par.beta_Y = 10**bestpars[orderedpars['beta_Y']]
par.K_IPTG = 10**bestpars[orderedpars['K_IPTG']]
par.K_AHL = 10**bestpars[orderedpars['K_AHL']]
par.K_LACI = 10**bestpars[orderedpars['K_LACI']]
par.K_TETR = 10**bestpars[orderedpars['K_TETR']]
par.K_ATC = 10**bestpars[orderedpars['K_ATC']]
par.n_LACI = 10**bestpars[orderedpars['n_LACI']]
par.n_AHL = 10**bestpars[orderedpars['n_AHL']]
par.n_TETR = 10**bestpars[orderedpars['n_TETR']]
#par.delta_X = bestpars[orderedpars['delta_X']]
#par.delta_Y = bestpars[orderedpars['delta_Y']]
par.delta_X = 1.0
par.delta_Y = 1.0
else:
# Some example interesting parameters in case that a file is missing
par.alpha_X = (10**2.65397418e+00)*1.67-404.74
par.alpha_Y = 10**2.64892714e+00
par.beta_X = (10**2.39798631e+00)*1.67
par.beta_Y = 10**2.50684751e+00
#par.K_IPTG = 10**-2.84705254e-01
par.K_IPTG = 10**(0.0827)
par.K_AHL = 10**2.16683127e+00
par.K_LACI = 10**-1.628084364e+00 # strength of Y on X
par.K_TETR = (10**-0.3461396e+00)/1.67 # strength of X on Y
par.K_ATC = 10**-9.2435282e-01
par.n_LACI = 10**0.58215
par.n_AHL = 10**0.22496
par.n_TETR = 10**0.14035
# par.delta_X = bestpars[orderedpars['delta_X']]
# par.delta_Y = bestpars[orderedpars['delta_Y']]
par.delta_X = 1.0
par.delta_Y = 1.0
print("loglikelihood: ", loglikelihood(fll.df,[par.alpha_X, par.alpha_Y,
par.beta_X, par.beta_Y, par.K_IPTG, par.K_AHL, par.K_LACI, par.K_TETR,
par.K_ATC, par.n_LACI, par.n_AHL, par.n_TETR]))
#IPTGconditions = [0,0.0625,0.09,0.125,0.16,0.5,1,10]
IPTGconditions = [0,0.125,10]
columns = ['RED_median_normed','GREEN_median_normed']
Dcolumns = ['RED_var','GREEN_var']
fig = plt.figure(constrained_layout = False, figsize = figsize)
gs = gridspec.GridSpec(len(IPTGconditions), len(columns))
for icond,cond in enumerate(IPTGconditions): # for each row of the plotgrid
rowsdf = fll.df[fll.df['IPTG']==cond] # these is the subdataframe with the condition of the gridrow
sslist = [] # list with the steady states found
if bifurcation_line is False:
for irow,row in rowsdf.iterrows(): # for each condition let's compute the steady states
chem.AHL = row['AHL']
chem.IPTG = row['IPTG']
chem.aTc = row['aTc']
steadystates = steady_states(np.log10(par.alpha_X+eps),np.log10(par.alpha_X+par.beta_X-eps),1000,par,chem)
steadystates = [ s for s in steadystates if s['stab']=='stable'] # only plotting stable states
for ss in steadystates:
if (ss['X']>0 and ss['Y']>0):
sslist.append([chem.AHL,ss['X'],ss['Y']])
sslist = np.array(sslist)
elif bifurcation_line is True:
if cond > 9: # this regulation takes into account that IPTG seems to saturate the bacterial behaviour for large concentrations
xcond = 7
else:
xcond = cond
s1,s2,u = getbifurcationcurves_AHL(limAHL = [1E-6,10], npoints = 1000, IPTG=xcond, ATC=0)
if len(u)>0:
u = np.array([cp for cp in u if cp[0]>1E-5]) # this line avoids some spurious unstable states detected for extreme values of IPTG
print ('unstable line',len(u))
for icol,column in enumerate(columns):
axes = plt.subplot(gs[icond,icol])
if sslist != []:
for ss in sslist:
if ss[0] > 0:
plt.plot([np.log10(ss[0])],[ss[icol+1]],'s',markersize = 5,
color =sbcolorcycledark[3-icol], zorder = 10)
else: # if AHL = 0
plt.plot([-5],[ss[icol+1]],'s',markersize = 5,
color =sbcolorcycledark[3-icol], zorder = 10)
if bifurcation_line is True:
if icol == 0:
plt.plot(np.log10(s1[:,0]), s1[:,1],'-',color =sbcolorcycledark[3-icol])
if len(s2)>0:
plt.plot(np.log10(s2[:,0]), s2[:,1],'-',color =sbcolorcycledark[3-icol])
if len(u)>0:
plt.plot(np.log10(u[:,0]), u[:,1],':',color =sbcolorcycledark[3-icol])
else:
y1 = flow(s1,par.alpha_Y,parr = par, chh = chem)[1]/par.delta_Y+par.alpha_Y
plt.plot(np.log10(s1[:,0]), y1[:,1],'-',color =sbcolorcycledark[3-icol])
if len(s2)>0:
y2 = flow(s2,par.alpha_Y,parr = par, chh = chem)[1]/par.delta_Y+par.alpha_Y
plt.plot(np.log10(s2[:,0]), y2[:,1],'-',color =sbcolorcycledark[3-icol])
if len(u)>0:
yu = flow(u,par.alpha_Y,parr = par, chh = chem)[1]/par.delta_Y+par.alpha_Y
plt.plot(np.log10(u[:,0]), yu[:,1],':',color =sbcolorcycledark[3-icol])
for rrow in rowsdf.iterrows():
if rrow[1]['AHL']>0: # iterrows returns a tuple, element 1 is the info
plt.errorbar([np.log10(rrow[1]['AHL'])],[rrow[1][column]],[np.sqrt(rrow[1][Dcolumns[icol]])],
mfc =sbcolorcyclebright[3-icol], color =sbcolorcyclebright[3-icol],
fmt = 'o', markersize = 5, zorder = -1, markeredgewidth = 0.5, mec = sbcolorcycledark[3-icol])
else : # if AHL = 0
plt.errorbar([-6],[rrow[1][column]],[np.sqrt(rrow[1][Dcolumns[icol]])],
mfc =sbcolorcyclebright[3-icol], color =sbcolorcyclebright[3-icol],
fmt = '<', markersize = 5, zorder = -1, markeredgewidth = 0.5, mec = sbcolorcycledark[3-icol])
if (icond == len(IPTGconditions)-1):
plt.xlabel('$\\log_{10}([AHL])$ ($\\mu M$)')
if (icol == 0 and icond == len(IPTGconditions)//2):
axes.set_ylabel('Fluorescence mCherry')
axes.yaxis.label.set_color('red')
if (icol == 1 and icond == len(IPTGconditions)//2):
axes.set_ylabel('Fluorescence GFP')
axes.yaxis.label.set_color('green')
if (icol == 0):
plt.text(-4,800,"[IPTG] = "+str(IPTGconditions[icond])+" mM", fontsize = 12)
axes.set_ylim([220,1000])
if (icol ==1 ):
axes.yaxis.tick_right()
axes.yaxis.set_label_position("right")
axes.set_ylim([121,1200])
plt.tight_layout()
gs.update(wspace=0.1, hspace=0.1)
plt.savefig('testpars.pdf')
plt.show()
return par
def plot_stochasticdynamics(chain=1):
# Function to test and show indivudual trajectories and details of the dynamical system
condition = '60000'
chain = chain
data1 = np.load('dream/bsfit_sampled_params_chain_'+str(chain)+'_'+condition+'.npy')
logpsdata1 = np.load('dream/bsfit_logps_chain_'+str(chain)+'_'+condition+'.npy')
lklh_list = np.array([l[0] for l in logpsdata1])
sorted_idxs = lklh_list.argsort()
data1_sorted = data1[sorted_idxs]
bestpars = data1_sorted[-1]
print(bestpars)
ibestlklh = -1
par.alpha_X = 10**bestpars[orderedpars['alpha_X']]
par.alpha_Y = 10**bestpars[orderedpars['alpha_Y']]
par.beta_X = 10**bestpars[orderedpars['beta_X']]
par.beta_Y = 10**bestpars[orderedpars['beta_Y']]
par.K_IPTG = 10**bestpars[orderedpars['K_IPTG']]
par.K_AHL = 10**bestpars[orderedpars['K_AHL']]
par.K_LACI = 10**bestpars[orderedpars['K_LACI']]
par.K_TETR = 10**bestpars[orderedpars['K_TETR']]
par.K_ATC = 10**bestpars[orderedpars['K_ATC']]
par.n_LACI = 10**bestpars[orderedpars['n_LACI']]
par.n_AHL = 10**bestpars[orderedpars['n_AHL']]
par.n_TETR = 10**bestpars[orderedpars['n_TETR']]
#par.delta_X = bestpars[orderedpars['delta_X']]
#par.delta_Y = bestpars[orderedpars['delta_Y']]
par.delta_X = 1.0
par.delta_Y = 1.0
chem.AHL = 10
chem.IPTG = 0.0625
chem.aTc = 0.0
# x-nullcline dotx = 0
ylist = np.linspace(par.alpha_Y,par.alpha_Y+par.beta_Y,500)
# xnull = flow(0,ylist)[0]
xnull = flow(par.alpha_X,ylist,chh=chem,parr = par)[0]+par.alpha_X
print('xnull', xnull)
# y-nullcline doty = 0
xlist = np.linspace(par.alpha_X,par.alpha_X+par.beta_X,500)
# ynull = flow(xlist,0)[1]
ynull = flow(xlist,par.alpha_Y,chh=chem,parr = par)[1]+par.alpha_Y
plt.plot(xnull,ylist,'-b')
plt.plot(xlist,ynull,'-r')
# plot steady states
sss = steady_states(np.log10(par.alpha_X+eps),np.log10(par.alpha_X+par.beta_X-eps),1000,par,chem)
print(sss)
for ss in sss:
if ss['stab'] == "stable":
plt.plot([ss['X']],[ss['Y']],'ok')
if ss['stab'] == "unstable":
plt.plot([ss['X']],[ss['Y']],'ow',markeredgecolor='k',markeredgewidth=2)
plt.xlim(200,1000)
plt.ylim(200,1000)
# stochastic trajectory
x0,y0 = 430,780
timeIntegration = 100
dt = 0.01
for j in range(10):
traj = integration(totaltime = timeIntegration, dt = dt, initcond=[x0,y0], result = "traj",
stochastic = True, volume = 10, parr = par, chh = chem)
plt.plot(traj[0],traj[1],'g',lw=1)
plt.show()
#########################################################################
######################## DIFFUSION OF SIGNALS
##########################################################################
def bist_plot_2D(mode = "stab", varx = "AHL", vary = "IPTG", rangex = [-1,-4], rangey = [-2,2], nprec = 30):
'''
Plot a 2d histogram with the endpoint of N*M pairs of conditions that consists
on logarithmically spaced rangex and rangy of varx and vary parameters
each axis contains nprec points
mode = "stab" then the program finds the steady state and plots
accordingly to the number and nature of the steady states
if mode = "int" then the program integrates two high and low given conditions
and plots accordingly to the number and nature of the steady states
'''
global par
par = getParametersFromMCMC()
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(5,5))
global pardict
chem_temp = copy.deepcopy(ch) # copy of pardict to avoid its modification and restore it
# at the end of the function call
nprecx = nprec
nprecy = nprec
xarray = np.logspace(rangex[0],rangex[1],nprecx)
yarray = np.logspace(rangey[0],rangey[1],nprecy)
F1 = np.ndarray(shape=[nprecx,nprecy])# F1 will contain the values of the expression to plot
F2 = np.ndarray(shape=[nprecx,nprecy])# F2 will contain the values of the expression to plot
for ix,x in enumerate(xarray):
for iy,y in enumerate(yarray):
setattr(chem_temp,varx,x)
setattr(chem_temp,vary,y)
if mode == "stab":
ss = steady_states(np.log10(par.alpha_X+eps),np.log10(par.alpha_X+par.beta_X-eps),1000,parr = par, chh = chem_temp)
uniquess = []
for state in ss:
stateisunique = True
for uniquestate in uniquess:
if abs(state['X']-uniquestate['X'])<0.001:
stateisunique = False
if stateisunique:
uniquess.append(state)
ss = uniquess
if len(ss) == 1:
colorcoord = np.log(ss[0]['Y'])-np.log(ss[0]['X']) # negative -> red, positive -> green
colorcoord = 0.5*(colorcoord+0.5) # linear transformation so neutral is at 0.5 of the colorscale
colorcoord = max(colorcoord,0) # set limits of the color
colorcoord = min(colorcoord,1) # set limits of the color
# print "state",np.log(ss[0]['X']),np.log(ss[0]['Y']),np.log(ss[0]['X'])-np.log(ss[0]['Y'])
F1[iy,ix] = colorcoord
F2[iy,ix] = 0
elif len(ss) >1:
# Choosing among the possible steady states
colorcoord = -np.inf
isstate = 100
for isss,sss in enumerate(ss):
if sss['Y'] > colorcoord:
colorcoord = sss['Y']
isstate = isss
print(varx, x, vary, y)
colorcoord = np.log(ss[isstate]['Y'])-np.log(ss[isstate]['X']) # negative -> red, positive -> green
colorcoord = 0.5*(colorcoord+0.5) # linear transformation so neutral is at 0.5 of the colorscale
colorcoord = max(colorcoord,0) # set limits of the color
colorcoord = min(colorcoord,1) # set limits of the color
# print "state",np.log(ss[0]['X']),np.log(ss[0]['Y']),np.log(ss[0]['X'])-np.log(ss[0]['Y'])
F1[iy,ix] = colorcoord
F2[iy,ix] = 1
# Differnt color for multistability
# F1[iy,ix] = 0 # whatever
# F2[iy,ix] = 1
else:
print("No stability states found!")
elif mode == "int":
# Setting initial condition with a preintegration (overnight culture)
setattr(chem_temp,'AHL',0)
setattr(chem_temp,'aTc',0)
setattr(chem_temp,'IPTG',1)
[Xini,Yini,t] = integration(totaltime = integdict['totaltime'], dt=integdict['dt'],
chh = chem_temp, result = 'end')
setattr(chem_temp,varx,x)
setattr(chem_temp,vary,y)
[X,Y,t]=integration(totaltime = integdict['totaltime'], initcond = [Xini,Yini],
dt=integdict['dt'], chh = chem_temp, result = 'end')
colorcoord = np.log(Y)-np.log(X) # negative -> red, positive -> green
colorcoord = 0.5*(colorcoord+0.5) # linear transformation so neutral is at 0.5 of the colorscale
colorcoord = max(colorcoord,0) # set limits of the color
colorcoord = min(colorcoord,1) # set limits of the color
F1[iy,ix] = colorcoord
F2[iy,ix] = 0
cmap = cm.get_cmap('RedtoGreen')
K1 = ax.pcolor(F1, cmap = 'RedtoGreen',rasterized=True)
K1 = ax.pcolor(F2, cmap = 'AlphatoBlue',rasterized=True)
K1.set_edgecolor('face')
leftvalue = int(np.ceil(rangex[0]))
rightvalue = int(np.floor(rangex[1]))