11import cr_mech_coli as crm
22import cr_mech_coli .crm_fit as crm_fit
3-
3+ from functools import partial
44import numpy as np
5- import matplotlib .pyplot as plt
6-
7- from bayes_opt import BayesianOptimization , acquisition
85
96
107def extract_data (image_timesteps , n_vertices ):
@@ -16,54 +13,36 @@ def extract_data(image_timesteps, n_vertices):
1613 return data
1714
1815
19- def cost (data , settings , init_pos , * param ):
16+ def cost_bacterialrods (data , settings , init_pos , param ):
2017 (days , x_target ) = data
2118 container = crm_fit .predict (param , init_pos , settings )
2219 if container is None :
2320 print ("Simulation Failed" )
24- exit ()
25- iterations = container .get_all_iterations ()
26- x_prediction = np .zeros (np .shape (x_target ))
27- delta_iter = np .mean (np .array (iterations )[1 :]- np .array (iterations )[:- 1 ])
28- ## TODO why is saved iterations step changes from 952 to 953 ??
29- iter_data = delta_iter * (np .array (days )- days [0 ]+ 1 )
30- ind_last = np .argmin (np .abs (iter_data [- 1 ]- iterations ))
31- i = 0
32- for iter in iterations [:ind_last + 1 ]:
33- if np .any (np .abs (iter_data - iter ) <= 1. ):
34- cells = container .get_cells_at_iteration (iter )
35- keys = sorted (cells .keys ())
36- # what is the last dimension: why 3 and not 2 ?
37- pos = np .array ([cells [key ][0 ].pos for key in keys ])[:, :, :- 1 ]
38- x_prediction [i ] = pos
39- i += 1
40- return np .mean (squared_difference (x_target , x_prediction ))
21+ return 1e10
22+ else :
23+ iterations = container .get_all_iterations ()
24+ x_prediction = np .zeros (np .shape (x_target ))
25+ delta_iter = np .mean (np .array (iterations )[1 :]- np .array (iterations )[:- 1 ])
26+ ## TODO why is saved iterations step changes from 952 to 953 ??
27+ iter_data = delta_iter * (np .array (days )- days [0 ]+ 1 )
28+ ind_last = np .argmin (np .abs (iter_data [- 1 ]- iterations ))
29+ i = 0
30+ for iter in iterations [:ind_last + 1 ]:
31+ if np .any (np .abs (iter_data - iter ) <= 1. ):
32+ cells = container .get_cells_at_iteration (iter )
33+ keys = sorted (cells .keys ())
34+ # what is the last dimension: why 3 and not 2 ?
35+ pos = np .array ([cells [key ][0 ].pos for key in keys ])[:, :, :- 1 ]
36+ x_prediction [i ] = pos
37+ i += 1
38+ return np .mean (squared_difference (x_target , x_prediction ))
4139
4240
4341def squared_difference (x_target , x_prediction ):
4442 return (x_target - x_prediction )** 2
4543
4644
47- def posterior (optimizer , grid ):
48- mu , sigma = optimizer ._gp .predict (grid , return_std = True )
49- return mu , sigma
50-
51-
52- def plot_objective_GP (optimizer , bnds , name = '' ):
53- for k in bnds .keys ():
54- fig , ax = plt .subplots ()
55- x_gp = np .linspace (* bnds [k ], 100 )
56- mean_gp , sigma_gp = posterior (optimizer , x_gp .reshape (- 1 , 1 ))
57- ax .plot (x_gp , mean_gp , label = k )
58- ax .fill_between (x_gp , mean_gp + sigma_gp , mean_gp - sigma_gp , alpha = 0.1 )
59- ax .scatter (optimizer .space .params .flatten (), optimizer .space .target , c = "red" , s = 50 , zorder = 10 )
60- ax .legend (fontsize = 12 )
61- plt .savefig (f'{ k } _{ name } ' + '.png' , bbox_inches = 'tight' )
62- plt .close (fig )
63-
64-
65-
66- def optimize_bacterialrods_main ():
45+ def create_test_ABM_framework ():
6746 n_vertices = 8
6847 # Extract data from masks which have been previously generated
6948 image_timesteps = ['42' , '43' , '44' , '45' , '46' , '47' , '48' , '49' , '52' ]
@@ -72,41 +51,20 @@ def optimize_bacterialrods_main():
7251 # Target/model/simulation
7352 # Define settings required to run simulation
7453 settings = crm_fit .Settings .from_toml ("data/crm_fit/0001/settings.toml" )
75- settings .constants .n_vertices = n_vertices
7654 settings .constants .n_saves = 15
7755 settings .others = crm_fit .Others (True )
56+ return data , settings
57+
7858
79- #settings.parameters.damping = crm_fit.SampledFloat(min=0, max=2.5, initial=1.5)
80- settings .parameters .damping = 2.0
81- settings .parameters .potential_type .Mie .en = 10.
82- settings .parameters .potential_type .Mie .em = 1.5
59+ def main_bacterialrods_optimization (optimizer , update_ABM = None ):
60+ # Define ABM framework
61+ data , settings = create_test_ABM_framework ()
62+ if update_ABM is not None :
63+ settings = update_ABM (settings )
8364 lower , upper , x0 , param_infos , constants , constant_infos = settings .generate_optimization_infos (len (data [1 ][0 ]))
65+ bnds_dict = {p_inf [0 ]: (u_b , l_b ) for u_b , l_b , p_inf in zip (lower , upper , param_infos )}
8466 print (param_infos )
85-
86- # Define the cost function with arguments as optimizes parameters:
87- #cost_for_optimization = lambda Damping, Strength: cost(data, settings, data[1][0], Damping, Strength)
88- #cost_for_optimization = lambda Damping: cost(data, settings, data[1][0], Damping)
89- cost_for_optimization = lambda Strength : cost (data , settings , data [1 ][0 ], Strength )
90-
91- N_iter = 20
92- acq = acquisition .ExpectedImprovement (1. ) #ProbabilityOfImprovement(1.) #UpperConfidenceBound(kappa=1.)#
93- bnds = {p_inf [0 ]: (u_b , l_b ) for u_b , l_b , p_inf in zip (lower , upper , param_infos )}
94- optimizer = BayesianOptimization (
95- f = None ,
96- acquisition_function = acq ,
97- pbounds = bnds ,
98- verbose = 2 ,
99- random_state = 17695 ,
100- )
101- for j in range (N_iter ):
102- next_params = optimizer .suggest ()
103- target = cost_for_optimization (** next_params )
104- optimizer .register (
105- params = next_params ,
106- target = target ,
107- )
108- plot_objective_GP (optimizer , bnds , name = f'EI_{ j } ' )
109-
110-
111- if __name__ == "__main__" :
112- optimize_bacterialrods_main ()
67+ cost_for_optimization = partial (cost_bacterialrods , data , settings , data [1 ][0 ])
68+ res = optimizer (cost_for_optimization , [bnds_dict [k ] for k in bnds_dict .keys ()])
69+ print (res .x , res .fun )
70+ return res
0 commit comments