-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparameter_fitting_selfadaptivesigma_fullmodel.py
471 lines (363 loc) · 19.6 KB
/
parameter_fitting_selfadaptivesigma_fullmodel.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
''' Authors: Katinka den Nijs & Robin van den Berg '''
import multiprocessing
import pandas as pd
import numpy as np
from multiprocessing import Pool, cpu_count
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
from scipy.optimize import fsolve, root
import random
from numba import jit
import math
import time
from tqdm import tqdm
from mpl_toolkits import mplot3d
class full_model(object):
""" A class containing the parameters, equations and necessary functions for the standard Martinez model """
def __init__(self, CD40, mu_r, sigma_r, mu_b, sigma_b, mu_p, sigma_p):
self.CD40 = CD40
self.mu_r = mu_r
self.sigma_r = sigma_r
self.mu_b = mu_b
self.sigma_b = sigma_b
self.mu_p = mu_p
self.sigma_p = sigma_p
# Dissociation constant
self.k_p = 1
self.k_b = 1
self.k_r = 1
# Degradation rate
self.l_p = 1
self.l_b = 1
self.l_r = 1
def equation_irf(self, r):
drdt = (self.mu_r + self.sigma_r * r ** 2 / (self.k_r ** 2 + r ** 2) + self.CD40 - \
self.l_r * r)
return drdt
def equation_bcl_GC(self, b):
dbdt = self.mu_b + (self.sigma_b * self.k_p ** 2) / (self.k_p ** 2 + np.mean(inter1_data_BLIMP) ** 2) * (
self.k_b ** 2) / (self.k_b ** 2 + b ** 2) * (self.k_r ** 2) / \
(self.k_r ** 2 + np.mean(inter1_data_IRF) ** 2) - (self.l_p) * b
return dbdt
def equation_bcl_PC(self, b):
dbdt = self.mu_b + (self.sigma_b * self.k_p ** 2) / (self.k_p ** 2 + np.mean(inter2_data_BLIMP) ** 2) * (
self.k_b ** 2) / \
(self.k_b ** 2 + b ** 2) * (self.k_r ** 2) / (self.k_r ** 2 + np.mean(inter2_data_IRF) ** 2) - (
self.l_p) * b
return dbdt
def equation_blimp_GC(self, p):
dpdt = self.mu_p + (self.sigma_p * self.k_b ** 2) / (self.k_b ** 2 + np.mean(inter1_data_BCL) ** 2) + \
(self.sigma_p * np.mean(inter1_data_IRF) ** 2) / (
self.k_r ** 2 + np.mean(inter1_data_IRF) ** 2) - self.l_p * p
return dpdt
def equation_blimp_PC(self, p):
dpdt = self.mu_p + (self.sigma_p * self.k_b ** 2) / (self.k_b ** 2 + np.mean(inter2_data_BCL) ** 2) + \
(self.sigma_p * np.mean(inter2_data_IRF) ** 2) / (
self.k_r ** 2 + np.mean(inter2_data_IRF) ** 2) - self.l_p * p
return dpdt
def calc_zeropoints(self):
self.intersections_irf = root(self.equation_irf, [0., 8, 200], method='lm')
self.intersections_bcl_GC = root(self.equation_bcl_GC, np.mean(inter1_data_BCL), method='lm')
self.intersections_bcl_PC = root(self.equation_bcl_PC, np.mean(inter2_data_BCL), method='lm')
self.intersections_blimp_GC = root(self.equation_blimp_GC, np.mean(inter1_data_BLIMP), method='lm')
self.intersections_blimp_PC = root(self.equation_blimp_PC, np.mean(inter2_data_BLIMP), method='lm')
return (self.intersections_irf.x, [self.intersections_bcl_GC.x, \
self.intersections_bcl_PC.x], [self.intersections_blimp_GC.x, \
self.intersections_blimp_PC.x])
def plot(self, name='test'):
# intersections = np.sort(intersections)
r_list = np.arange(0, 12, 0.001)
drdt = self.equation_irf(r_list)
dbdt_GC = self.equation_bcl_GC(r_list)
dbdt_PC = self.equation_bcl_PC(r_list)
dpdt_GC = self.equation_blimp_GC(r_list)
dpdt_PC = self.equation_blimp_PC(r_list)
# intersections = self.intersections.x
fig = plt.figure()
plt.title("{}: With intersections: {}".format(name, self.intersections_irf.x))
# plt.plot(r_list + intersections[1], drdt - drdt[0])
plt.plot(r_list, drdt, label='fit')
plt.scatter(self.intersections_irf.x, [0, 0, 0], marker='x')
plt.scatter(inter1_data_IRF, np.zeros(len(inter1_data_IRF)), label='GC')
plt.scatter(inter2_data_IRF, np.zeros(len(inter2_data_IRF)), label='PC')
plt.axhline(y=0, color='grey', linestyle='--')
# plt.ylim(-0.05 * 10 ** -8, 0.09 * 10 ** (-8))
# plt.xlim(3, 12)
plt.xlabel('r', fontsize=14)
plt.ylabel('drdt', fontsize=14)
plt.legend(fontsize=14)
fig.savefig("AffymetrixData{}_IRF4.png".format(name.capitalize()))
plt.close(fig)
fig = plt.figure()
plt.title("{}: With intersections: {}".format(name, [self.intersections_bcl_GC.x, self.intersections_bcl_PC.x]))
# plt.plot(r_list + intersections[1], drdt - drdt[0])
plt.plot(r_list, dbdt_PC, label='fit PC')
plt.plot(r_list, dbdt_GC, label='fit GC')
plt.scatter([self.intersections_bcl_GC.x, self.intersections_bcl_PC.x], [0, 0], marker='x')
plt.scatter(inter1_data_BCL, np.zeros(len(inter1_data_BCL)), label='GC')
plt.scatter(inter2_data_BCL, np.zeros(len(inter2_data_BCL)), label='PC')
plt.axhline(y=0, color='grey', linestyle='--')
# plt.ylim(-0.05 * 10 ** -8, 0.09 * 10 ** (-8))
# plt.xlim(3, 12)
plt.xlabel('b', fontsize=14)
plt.ylabel('dbdt', fontsize=14)
plt.legend(fontsize=14)
fig.savefig("AffymetrixData{}_BCL.png".format(name.capitalize()))
plt.close(fig)
fig = plt.figure()
plt.title(
"{}: With intersections: {}".format(name, [self.intersections_blimp_GC.x, self.intersections_blimp_PC.x]))
# plt.plot(r_list + intersections[1], drdt - drdt[0])
plt.plot(r_list, dpdt_PC, label='fit PC')
plt.plot(r_list, dpdt_GC, label='fit GC')
plt.scatter([self.intersections_blimp_GC.x, self.intersections_blimp_PC.x], [0, 0], marker='x')
plt.scatter(inter1_data_BLIMP, np.zeros(len(inter1_data_BLIMP)), label='GC')
plt.scatter(inter2_data_BLIMP, np.zeros(len(inter2_data_BLIMP)), label='PC')
plt.axhline(y=0, color='grey', linestyle='--')
# plt.ylim(-0.05 * 10 ** -8, 0.09 * 10 ** (-8))
# plt.xlim(3, 12)
plt.xlabel('p', fontsize=14)
plt.ylabel('dpdt', fontsize=14)
plt.legend(fontsize=14)
fig.savefig("AffymetrixData{}_BLIMP.png".format(name.capitalize()))
plt.close(fig)
def fitness(ind):
'''
Calculates the fitness of an individual as the mse on the time series
:param ind: an array containing the parameters we want to be fitting
:return: the fitness of an individual, the lower the better tho
'''
ind = ind[:int(len(ind) / 2)]
model_ind = full_model(*ind)
intersections = model_ind.calc_zeropoints()
beta = (model_ind.mu_r + model_ind.CD40 + model_ind.sigma_r) / (model_ind.l_r * model_ind.k_r)
p = - model_ind.sigma_r / (model_ind.l_r * model_ind.k_r) + beta
if (beta ** 2 > 3) and (beta ** 3 + (beta ** 2 - 3) ** (3 / 2) - 9 * beta / 2 > - 27 / 2 * p) and \
(beta ** 3 - (beta ** 2 - 3) ** (3 / 2) - 9 * beta / 2 < - 27 / 2 * p) and (beta > 0) and (p > 0) \
and (ind[0] > 0) and (ind[1] > 0) and (ind[2] > 0) and (ind[3] > 0) and (ind[4] > 0):
return abs(sum((min(intersections[0]) - inter1_data_IRF) / inter1_data_IRF)) / len(inter1_data_IRF) + \
abs(sum((max(intersections[0]) - inter2_data_IRF) / inter2_data_IRF)) / len(inter2_data_IRF) + \
abs(sum((max(intersections[1]) - inter1_data_BCL) / inter1_data_BCL)) / len(inter1_data_BCL) + \
abs(sum((min(intersections[1]) - inter2_data_BCL) / inter2_data_BCL)) / len(inter2_data_BCL) + \
abs(sum((min(intersections[2]) - inter1_data_BLIMP) / inter1_data_BLIMP)) / len(inter1_data_BLIMP) + \
abs(sum((max(intersections[2]) - inter2_data_BLIMP) / inter2_data_BLIMP)) / len(inter2_data_BLIMP)
else:
return 10000000
def mutation(child):
"""
Performs self-adaptive mutation
"""
if np.random.random() < mutation_chance:
num_of_sigmas = int(len(child) / 2)
# get new mutation step size for all parameters
child[num_of_sigmas:] = child[num_of_sigmas:] * np.exp(tau * np.random.normal(0, 1))
# mutate child
child[:num_of_sigmas] = abs(child[:num_of_sigmas] + np.random.normal(num_of_sigmas) * child[num_of_sigmas:])
return child
def crossover(population, fitnesses, k, best_sol):
"""
Performs uniform crossover with tournament selection
"""
nr_children = int(len(population) * frac_to_replace)
child = 1
indices_replaced = np.zeros(nr_children)
# start making offspring (two for each couple of parents)
while child < nr_children - 2:
parent1, idx1 = tournament_selection(population, k, fitnesses)
parent2, idx2 = tournament_selection(population, k, fitnesses)
# determine weights
weights = np.zeros(len_ind)
weights[:len_ind] = np.random.choice(np.array([0, 1]), size=len_ind)
np.random.shuffle(weights)
# perform crossover
offspring1 = weights * parent1 + (1 - weights) * parent2
offspring2 = (1 - weights) * parent1 + weights * parent2
ind_to_be_replaced_1, idx_replace1 = tournament_selection_worst(population, k, fitnesses, indices_replaced)
ind_to_be_replaced_2, idx_replace2 = tournament_selection_worst(population, k, fitnesses, indices_replaced)
indices_replaced[child] = idx_replace1
indices_replaced[child + 1] = idx_replace2
population[idx_replace1] = abs(offspring1)
population[idx_replace2] = abs(offspring2)
child += 2
population[0] = best_sol
return population
def tournament_selection_worst(sols, k, fitnesses, indices_replaced):
'''
Selects the best individuals out of k individuals
'''
best = -1
for i in range(k):
idx = np.random.randint(0, len(sols))
if (best == -1 or fitnesses[idx] > fitnesses[best]) and not (idx in indices_replaced):
best = idx
return sols[best], best
def tournament_selection(sols, k, fitnesses):
'''
Selects the best individuals out of k individuals
'''
best = -1
for i in range(k):
idx = np.random.randint(0, len(sols))
if best == -1 or fitnesses[idx] < fitnesses[best]:
best = idx
return sols[best], best
def init_pop(pop_size, num_variables):
population = np.ones((pop_size, num_variables)) * \
abs(np.array([np.random.normal(0.00005, 0.00025, pop_size), np.random.normal(0.1, 0.3, pop_size),
np.random.normal(2.6, 3, pop_size), np.random.normal(2, 2, pop_size),
np.random.normal(100, 20, pop_size), np.random.normal(0.000001, 0.000001, pop_size),
np.random.normal(9, 5, pop_size), # tot hier de
# waardes van de params, rest is sigmas
np.random.normal(0, 20, pop_size),
np.random.normal(0, 20, pop_size), np.random.normal(0, 20, pop_size),
np.random.normal(0, 20, pop_size), np.random.normal(0, 20, pop_size),
np.random.normal(0, 20, pop_size), np.random.normal(0, 20, pop_size)]).T)
return population
def initializer(d1_IRF, d2_IRF, d3_IRF, d1_BCL, d2_BCL, d3_BCL, d1_BLIMP, d2_BLIMP, d3_BLIMP):
global inter1_data_IRF
global inter2_data_IRF
global inter3_data_IRF
global inter1_data_BCL
global inter2_data_BCL
global inter3_data_BCL
global inter1_data_BLIMP
global inter2_data_BLIMP
global inter3_data_BLIMP
global tau
global mutation_chance
inter1_data_IRF = d1_IRF
inter3_data_IRF = d3_IRF
inter2_data_IRF = d2_IRF
inter1_data_BCL = d1_BCL
inter3_data_BCL = d3_BCL
inter2_data_BCL = d2_BCL
inter1_data_BLIMP = d1_BLIMP
inter3_data_BLIMP = d3_BLIMP
inter2_data_BLIMP = d2_BLIMP
mutation_chance = 0.5
tau = 0.90
def run_evolutionary_algo(pop_size, num_variables, num_gen, tournament_size,
inter1_data_IRF, inter2_data_IRF, inter3_data_IRF,
inter1_data_BCL, inter2_data_BCL, inter3_data_BCL,
inter1_data_BLIMP, inter2_data_BLIMP, inter3_data_BLIMP):
"""
Run evolutionary algorithm in parallel
"""
len_ind = num_variables * 2
population = init_pop(pop_size=pop_size, num_variables=len_ind)
best_sol_current = None
best_fit_current = 100000000000
mu_r_list = np.zeros(num_gen * pop_size)
sigma_r_list = np.zeros(num_gen * pop_size)
mu_b_list = np.zeros(num_gen * pop_size)
sigma_b_list = np.zeros(num_gen * pop_size)
mu_p_list = np.zeros(num_gen * pop_size)
sigma_p_list = np.zeros(num_gen * pop_size)
CD40_list = np.zeros(num_gen * pop_size)
fitness_list = np.zeros(num_gen * pop_size)
# start evolutionary algorithm
for gen in range(num_gen):
start_time = time.time()
pool_input = tuple(population)
# run the different solutions in parallel
pool = Pool(cpu_count(), initializer, (inter1_data_IRF, inter2_data_IRF, inter3_data_IRF,
inter1_data_BCL, inter2_data_BCL, inter3_data_BCL,
inter1_data_BLIMP, inter2_data_BLIMP, inter3_data_BLIMP))
fitnesses = pool.map(fitness, pool_input)
pool.close()
pool.join()
# save all data about the population
CD40_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = np.array(population)[:, 0]
mu_r_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = np.array(population)[:, 1]
sigma_r_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = np.array(population)[:, 2]
mu_b_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = np.array(population)[:, 3]
sigma_b_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = np.array(population)[:, 4]
mu_p_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = np.array(population)[:, 5]
sigma_p_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = np.array(population)[:, 6]
fitness_list[gen * len(fitnesses): (gen + 1) * len(fitnesses)] = fitnesses
best_fit_gen = min(fitnesses)
if best_fit_gen < best_fit_current:
best_sol_current = population[fitnesses.index(min(fitnesses))]
best_fit_current = min(fitnesses)
population = crossover(population, fitnesses, tournament_size, best_sol_current)
pool_input = tuple(population)
# run the different solutions in parallel
pool = Pool(cpu_count(), initializer, (inter1_data_IRF, inter2_data_IRF, inter3_data_IRF,
inter1_data_BCL, inter2_data_BCL, inter3_data_BCL,
inter1_data_BLIMP, inter2_data_BLIMP, inter3_data_BLIMP))
population = pool.map(mutation, pool_input)
pool.close()
pool.join()
print("Best fit and average fit at gen {}: \t {}, \t {}, time to run it {}".format(gen, best_fit_gen,
np.mean(fitnesses),
time.time() - start_time))
results = pd.DataFrame(data=np.array([CD40_list, mu_r_list, sigma_r_list,
mu_b_list, sigma_b_list, mu_p_list,
sigma_p_list, fitness_list]).T,
columns=['CD40', 'mu_r', 'sigma_r', 'mu_b', 'sigma_b',
'mu_p', 'sigma_p', 'fitness'])
results.to_csv('total_fitting_individuals_inclkandl.csv')
return best_fit_current, best_sol_current
if __name__ == '__main__':
# tau = 0.99 # needs to be changed in initializer function
# mutation_chance = 0.25 # needs to be changed in initializer function
crossover_chance = 0.25
frac_to_replace = 0.5
number_of_variables_to_fit = 7
tournament_size = 100
len_ind = number_of_variables_to_fit * 2 # times two for the sigmas
pop_size = 100000
num_gen = 25
# affymetrix_df = pd.read_csv('matrinez_data.csv') # change this in the initializer as well
affymetrix_df = pd.read_csv('wesenhagen_data.csv')
affymetrix_df = affymetrix_df.set_index('Sample')
affymetrix_df = affymetrix_df.divide(4)
inter1_data_IRF = np.append(affymetrix_df.loc['CB', 'IRF4'].values, affymetrix_df.loc['CC', 'IRF4'].values)
inter2_data_IRF = affymetrix_df.loc['PC', 'IRF4'].values
inter3_data_IRF = affymetrix_df.loc['CB', 'IRF4'].values
inter1_data_BCL = np.append(affymetrix_df.loc['CB', 'BCL6'].values, affymetrix_df.loc['CC', 'BCL6'].values)
inter2_data_BCL = affymetrix_df.loc['PC', 'BCL6'].values
inter3_data_BCL = affymetrix_df.loc['CB', 'BCL6'].values
inter1_data_BLIMP = np.append(affymetrix_df.loc['CB', 'PRDM1'].values, affymetrix_df.loc['CC', 'PRDM1'].values)
inter2_data_BLIMP = affymetrix_df.loc['PC', 'PRDM1'].values
inter3_data_BLIMP = affymetrix_df.loc['CB', 'PRDM1'].values
best_fitness, best_ind = run_evolutionary_algo(pop_size, number_of_variables_to_fit, num_gen, tournament_size,
inter1_data_IRF, inter2_data_IRF, inter3_data_IRF,
inter1_data_BCL, inter2_data_BCL, inter3_data_BCL,
inter1_data_BLIMP, inter2_data_BLIMP, inter3_data_BLIMP)
best_solution = full_model(*best_ind[:number_of_variables_to_fit])
print("De snijpunten met de x-as: ", best_solution.calc_zeropoints())
print('mu_r: {}, sigma_r: {}, mu_b: {}, sigma_b: {}, mu_p: {}, sigma_p: {}, CD40: {} '.format(best_solution.mu_r,
best_solution.sigma_r,
best_solution.mu_b,
best_solution.sigma_b,
best_solution.mu_p,
best_solution.sigma_p,
best_solution.CD40))
print("The fitness of our solution: ", fitness([best_solution.CD40, best_solution.mu_r, best_solution.sigma_r,
best_solution.mu_b, best_solution.sigma_b, best_solution.mu_p,
best_solution.sigma_p, 0, 0, 0, 0, 0, 0, 0]))
best_solution.plot('Ours')
mu_r = 0.1
sigma_r = 2.6
CD40 = 0.00001
lambda_r = 1
k_r = 1
beta = mu_r + CD40 + sigma_r / (lambda_r * k_r)
p = -sigma_r / (lambda_r * k_r) + beta
# beta = 12.76144062324778
# p = 0.004582577456956276
mu_b = 2
sigma_b = 100
mu_p = 10 ** (-6)
sigma_p = 9
sol_of_martinez = full_model(CD40, mu_r, sigma_r, mu_b, sigma_b, mu_p, sigma_p)
print('Martinez: mu: {}, sigma: {}, k: {}, lambda: {}, CD40: {} '.format(mu_r, CD40, sigma_r, lambda_r, k_r))
print("Location of the roots: ", sol_of_martinez.calc_zeropoints())
print("The fitness of the martinez solution: ", fitness([CD40, mu_r, sigma_r, mu_b, sigma_b, mu_p, sigma_p, 0, 0, 0,
0, 0, 0, 0]))
sol_of_martinez.plot('Martinez')