-
Notifications
You must be signed in to change notification settings - Fork 0
/
tauleap_simulation.py
403 lines (234 loc) · 9.42 KB
/
tauleap_simulation.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
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 7 11:05:49 2022
@author: asus
"""
import argparse
import configparser
import ast
import sys
import numpy as np
import pandas as pd
import typing
from enum import Enum
import os
from collections import namedtuple
#from itertools import cycle
import time
import datetime
# get the start time
st_sec = time.time()
st_date = datetime.datetime.now()
config = configparser.ConfigParser()
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="read configuration file.")
parser.add_argument('-run', help='run Tau-leap simulation given a configuration filename', action = "store_true")
parser.add_argument('-run_multiplesimulations', help='run a number of N Gillespie simulations given a configuration filename', action = "store_true")
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
args = parser.parse_args()
config.read(args.filename)
if args.verbose:
print("I am reading the configuration file {}".format(args.filename))
#config.read('configuration.txt')
def read_population():
"""This function reads population parameters from configuration file
"""
state = config.get('POPULATION', 'state')
def apply_pipe(func_list, obj):
for function in func_list:
obj = function(obj)
return obj
starting_state = apply_pipe([ast.literal_eval, np.array], state)
index = dict(config["INDEX"])
for key,value in index.items():
index[key] = int(value)
active_genes = index['active_genes']
inactive_genes = index['inactive_genes']
RNAs = index['rnas']
proteins = index['proteins']
return starting_state, active_genes, inactive_genes, RNAs, proteins
starting_state, active_genes, inactive_genes, RNAs, proteins = read_population()
def read_k_values():
"""This function reads k parameters from configuration file
"""
k_value = dict(config["RATES"])
for key,value in k_value.items():
k_value[key] = float(value)
rates = namedtuple("Rates",['ka', 'ki', 'k1', 'k2', 'k3', 'k4'])
rate = rates(ka = k_value['ka'],
ki = k_value['ki'],
k1 = k_value['k1'],
k2 = k_value['k2'],
k3 = k_value['k3'],
k4 = k_value['k4'])
return rate
rate = read_k_values()
def read_simulation_parameters():
"""This function reads simulation parameters from configuration file
"""
simulation = dict(config["SIMULATION"])
for key,value in simulation.items():
if key == 'dt':
simulation[key] = float(value)
else:
simulation[key] = int(value)
time_limit = simulation['time_limit']
N = simulation['n_simulations']
warmup_time = simulation['warmup_time']
seed_number = simulation['seed_number']
dt = simulation['dt']
return time_limit, N, warmup_time, seed_number, dt
time_limit, N, warmup_time, seed_number, dt = read_simulation_parameters()
actual_dir = os.getcwd()
file_path = r'{}\{}.csv'
#%%
def gene_activate(state):
return state[inactive_genes]*rate.ka
def gene_inactivate(state):
return state[active_genes]*rate.ki
def RNA_increase(state):
return state[active_genes]*rate.k1
def RNA_degrade(state):
return state[RNAs]*rate.k2
def Protein_increase(state):
return state[RNAs]*rate.k3
def Protein_degrade(state):
return state[proteins]*rate.k4
transitions = [RNA_increase, RNA_degrade,
Protein_increase, Protein_degrade]
class Transition(Enum):
"""Define all possible transitions"""
GENE_ACTIVATE = 'gene activate'
GENE_INACTIVATE = 'gene inactivate'
RNA_INCREASE = 'RNA increase'
RNA_DEGRADE = 'RNA degrade'
PROTEIN_INCREASE = 'Protein increase'
PROTEIN_DEGRADE = 'Protein degrade'
transition_names = [Transition.RNA_INCREASE, Transition.RNA_DEGRADE,
Transition.PROTEIN_INCREASE, Transition.PROTEIN_DEGRADE]
class Observation(typing.NamedTuple):
""" typing.NamedTuple class storing information
for each event in the simulation"""
state: typing.Any
time_of_observation: float
time_of_residency: float
#transition: Transition
transition_rates: typing.Any
n_reactions: typing.Any
mean: typing.Any
#%%
def update_state(state, n_reactions):
state[RNAs] += n_reactions[0]
state[RNAs] -= n_reactions[1]
state[proteins] += n_reactions[2]
state[proteins] -= n_reactions[3]
updated_state = state
return updated_state
def tauleap(starting_state, transitions):
state = starting_state
rates = np.array([f(state) for f in transitions])
mean = rates * dt
n_reactions = np.random.poisson(mean)
state = state.copy()
updated_state = update_state(state, n_reactions)
tauleap_result = [starting_state, updated_state, dt, rates, n_reactions, mean]
return tauleap_result
def evolution(time_limit, seed_number):
observed_states = []
state = starting_state
total_time = 0.0
np.random.seed(seed_number)
while total_time < time_limit:
tauleap_result = tauleap(starting_state = state, transitions = transitions)
rates = tauleap_result[3]
dt = tauleap_result[2]
observation_state = tauleap_result[0]
n_reactions = tauleap_result[4]
mean = tauleap_result[5]
observation = Observation(observation_state, total_time, dt, rates, n_reactions, mean)
observed_states.append(observation)
# Update time
total_time += dt
# Update starting state in tau leaping algorithm
state = state.copy()
state = tauleap_result[1]
return observed_states
if args.run:
simulation_results = evolution(time_limit = time_limit, seed_number = seed_number)
#%%
def create_dataframe(results):
""" This function creates a dataframe with 4 columns:
time of observation, gene activity, number of RNA molecules
and number of proteins.
"""
time_of_observation = []
number_of_RNA_molecules = []
number_of_proteins = []
gene_activity = []
residency_time = []
for observation in results:
time_of_observation.append(observation.time_of_observation)
number_of_RNA_molecules.append(observation.state[RNAs])
number_of_proteins.append(observation.state[proteins])
residency_time.append(observation.time_of_residency)
if observation.state[active_genes] > 0:
gene_activity.append(1)
else:
gene_activity.append(0)
d = {'Time': time_of_observation,
'Gene activity': gene_activity,
'Number of RNA molecules': number_of_RNA_molecules,
'Number of proteins': number_of_proteins,
'Residency Time': residency_time}
results_dataframe = pd.DataFrame(d)
return results_dataframe
if args.run:
df = create_dataframe(results = simulation_results)
df.to_csv(file_path.format(actual_dir,"tauleapsimulation_results"), sep =" ", index = None, header=True, mode = "w")
if args.run_multiplesimulations:
def create_multiplesimulations_dataframes(N):
"""This function makes multiple simulations and creates a list
of results dataframes (one results dataframe for each simulation)
Parameters
----------
N : int
number of simulations.
Returns
-------
list of results dataframe
"""
results_list = []
for n in range(1,N+1):
result = evolution(time_limit = time_limit, seed_number = n)
results_list.append(result)
dataframes_list = []
for result in results_list:
dataframe = create_dataframe(result)
dataframes_list.append(dataframe)
return dataframes_list
dataframes_list = create_multiplesimulations_dataframes(N)
def save_multiplesimulations_results(N, file_path = file_path):
"""This function saves dataframes of multiple simulations in tab separated CSV files
each one named as "results_seedn" with n that is the number of the random seed.
Parameters
N : int
number of simulations.
file_path : str, default is r"C:\\Users\asus\Desktop\{}.csv"
path to folder where files are saved. By default, it saves the files following the path \\Users\asus\Desktop.
You can change it in the configuration file.
"""
results_names = []
for n in range(1,N+1):
results_names.append("tauleapresults_seed"+str(n))
for dataframe, results in zip(dataframes_list, results_names):
dataframe.to_csv(file_path.format(actual_dir, results), sep=" ", index = None, header=True)
save_multiplesimulations_results(N)
print("My job is done. Enjoy data analysis !")
# get the end time
et_sec = time.time()
et_date = datetime.datetime.now()
# get the execution time
elapsed_time_sec = et_sec - st_sec
elapsed_time_date = et_date - st_date
print(" ")
print('Execution time: {}s ({})'.format(elapsed_time_sec, elapsed_time_date))