def main(): number_of_runs = 4 # You may put a direct path to a simulation of your choice here and comment out simulation_fname line below # simulation_fname = <direct path your simulation> simulation_fname = join(dirname(dirname(__file__)), 'cellsort_2D', 'cellsort_2D.cc3d') root_output_folder = join(expanduser('~'), 'CC3DCallerOutput') # this creates a list of simulation file names where simulation_fname is repeated number_of_runs times # you can create a list of different simulations if you want. sim_fnames = [simulation_fname] * number_of_runs ret_values = [] for i, sim_fname in enumerate(sim_fnames): cc3d_caller = CC3DCaller(cc3d_sim_fname=sim_fname, screenshot_output_frequency=10, output_dir=join(root_output_folder, f'cellsort_{i}'), result_identifier_tag=i) ret_value = cc3d_caller.run() ret_values.append(ret_value) print('return values', ret_values)
def generate_callable(self, run_idx=0): if self.__sim_input is not None: sim_input = self.__sim_input[run_idx] else: sim_input = None cc3d_caller = CC3DCaller(cc3d_sim_fname=simulation_fname, output_frequency=self.output_frequency, screenshot_output_frequency=self.screenshot_output_frequency, output_dir=self.get_run_output_dir(run_idx), result_identifier_tag=run_idx, sim_input=sim_input) return cc3d_caller
def main(): num_workers = 4 number_of_runs = 10 # You may put a direct path to a simulation of your choice here and comment out simulation_fname line below # simulation_fname = <direct path your simulation> simulation_fname = join(dirname(dirname(__file__)), 'cellsort_2D', 'cellsort_2D.cc3d') root_output_folder = join(expanduser('~'), 'CC3DCallerOutput') # this creates a list of simulation file names where simulation_fname is repeated number_of_runs times # you can create a list of different simulations if you want. sim_fnames = [simulation_fname] * number_of_runs tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() # Start workers num_consumers = multiprocessing.cpu_count() * 2 print('Creating %d consumers' % num_consumers) workers = [CC3DCallerWorker(tasks, results) for i in range(num_workers)] for w in workers: w.start() # Enqueue jobs for i, sim_fname in enumerate(sim_fnames): cc3d_caller = CC3DCaller(cc3d_sim_fname=sim_fname, screenshot_output_frequency=10, output_dir=join(root_output_folder, f'cellsort_{i}'), result_identifier_tag=i) tasks.put(cc3d_caller) # Add a stop task "poison pill" for each of the workers for i in range(num_workers): tasks.put(None) # Wait for all of the tasks to finish tasks.join() # Start printing results while number_of_runs: result = results.get() print('Result:', result) number_of_runs -= 1
def run_trials(num_runs, iteration_num, lam_trial): """ Runs simulation and store simulation results :param num_runs: number of simulation runs :param iteration_num: integer label for storing results according to an iteration :param lam_trial: chemotactic Lagrange multiplier to simulate :return: mean horizontal center of mass over all runs """ root_output_folder = join(res_output_root, f'iteration_{iteration_num}') tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() # Start workers workers = [CC3DCallerWorker(tasks, results) for i in range(num_workers)] [w.start() for w in workers] # Enqueue jobs for i in range(num_runs): cc3d_caller = CC3DCaller(cc3d_sim_fname=simulation_fname, output_frequency=10, screenshot_output_frequency=10, output_dir=join(root_output_folder, f'trial_{i}'), result_identifier_tag=i, sim_input=lam_trial ) tasks.put(cc3d_caller) # Add a stop task for each of worker for i in range(num_workers): tasks.put(None) # Wait for all of the tasks to finish tasks.join() # Return mean result trial_results = [] while num_runs: result = results.get() trial_results.append(result['result']) num_runs -= 1 return np.average(trial_results)
def main(): # Get the absolute path to the cc3d simulation file and output directory where results will be stored cc3d_sim_fname = join(dirname(__file__), sim_name) # where to find the cc3d simulation file output_dir = join(dirname(__file__), 'Results') # where results will be stored # Execute CC3D with a specified output frequency cc3d_caller = CC3DCaller(cc3d_sim_fname=cc3d_sim_fname, output_frequency=output_frequency, output_dir=output_dir) ret_val = cc3d_caller.run() # Run it! # Get the absolute path to the simulation directory, lattice data summary file and screenshot json sim_dir = join(dirname(__file__), 'Simulation') # where to find the CC3D model specification lds_file = standard_lds_file(output_dir) # lattice data summary file screenshot_spec = standard_screenshot_file(sim_dir) # screenshot json # Render results and store the renders in a specific location render_dir_abs = join(dirname(__file__), render_dir) # Storing here cc3d_renderer = CC3DRenderer(lds_file=lds_file, screenshot_spec=screenshot_spec, output_dir=render_dir_abs) cc3d_renderer.initialize( ) # Initialize CC3D rendering backend; we can do manipulations before and after this call cc3d_renderer.export_all() # Render and export all available results
def main(): # Set up file locations root = r'C:/CompuCell3D-py3-64bit/lib/site-packages/ProtocellSimulator/' project_name = 'ProtoCellularSim' simulation_file_path = join(root, project_name + '/' + project_name + '.cc3d') init_cells_file_path = join(root, project_name + '/' + 'init_cell_field.piff') variables_file = join(root, project_name + '/' + 'variables.csv') root_output_folder = join(root, project_name + '/' + 'Results') abbrevs = {'ProtoCellularSim': 'proto'} gen_file_prefix = 'gen_' # record_file = 'fitness_records.csv' # record_file = 'fit_rec_55_COM.csv' # rec_file_prefix = 'fit_' # Set up parallel processing / multi-threading parameters # cpus = 4 # threads_per_cpu = cpus # work_nodes = cpus * threads_per_cpu work_nodes = 4 # ############################################################################ 1 / 16 grid_dim = int(work_nodes**0.5) phenomes_per_sim = 1 # ###################################################################### 1 / 4 repeats = int(work_nodes / phenomes_per_sim) # Set up simulation parameters cell_diam = 10 actuate_scale = 2 actuate_period = 100 num_actuation_cycles = 10 # ################################################################### 10 / 100 key2name = { 3: 'ProtocellPassive', 4: 'ProtocellActiveA', 5: 'ProtocellActiveB' } num_active_types = np.array( [int('Active' in x) for x in key2name.values()]).sum() max_mcs = ((num_active_types + 2) * num_actuation_cycles + 1) * actuate_period # num_active_types + 2 ??? phenome_scaling = [ 1, 1 ] # ################################################# [1, 1] / [2, 2] / [3, 3] scaling_mode = 'exp' # ########################################################'tes' / 'exp' phenome_mode = 'car' # ######################################################## 'car' / 'hexH' 'hexV' phenome_dims = [5, 5] phenome_format = '' for d in phenome_dims: phenome_format += str(d) zone_size = int(10 * np.ceil( np.sum([(cell_diam * phenome_scaling[p] * actuate_scale * phenome_dims[p])**2 for p in range(0, len(phenome_dims))])**0.5 / 10)) zone_size = 400 # ################################################# 120 / 200 corner_offset = [ int((zone_size - 2 - phenome_dims[p] * cell_diam * phenome_scaling[p]) / 2) + 1 for p in range(0, len(phenome_dims)) ] name2dims = {} for name in key2name.values(): name2dims[name] = [cell_diam] * 2 sim_dim = int(grid_dim * zone_size) # Write variables to file pd.DataFrame( np.array([ ['cell diam', cell_diam], ['actuate scale', actuate_scale], ['actuate period', actuate_period], ['num active types', num_active_types], ['max mcs', max_mcs], ['work nodes', 1], # ###################### work_nodes ['sim dim', sim_dim] ]), None, ['Name', 'Value']).to_csv(variables_file, index=False) # Set up evolution parameters track_flag = False evolve_flag = True randomise_flag = True # rep_seed = ['5555433540354445544405540'] # rep_seed = ['5550055444554455544455544'] # good, one cell is sub-optimal # rep_seed = ['4444444444544455545555555'] # rep_seed = ['4000444044540455545555555'] # <<< crafted1 # rep_seed = ['5350305554554405444054044'] # <<< first success # traj_label = 'trial1_' # rep_seed = ['0333550354405444554430044'] # <<< second attempt # rep_seed = ['5355535455540454404440444'] # <<< third attempt # traj_label = 'trial3_' # rep_seed = ['5350055444554445544455543'] # <<< trial 4 # traj_label = 'trial4_' # rep_seed = ['4444444444544455545555555'] # traj_label = 'custom_' rep_seed = ['4444444444544455555555555'] traj_label = 'custom2r_' # rep_seed = ['4455544455444554445544555'] # traj_label = 'custom2u_' # rep_seed = ['5555555555544454444444444'] # traj_label = 'custom2l_' # rep_seed = ['5554455444554445544455544'] # traj_label = 'custom2d_' # rep_seed = ['4000050000000000000000000'] # <<< two cell example # traj_label = 'twoCell_' # rep_seed = ['0350500554303403334050044'] # <<< combination # rep_seed = '0404035350430040340534003' # <<<< random init_gen = 0 number_of_generations = 20 # ########################################################### 10 / 50 fitness_function = 'COM' survival_prop = 0.2 # 0.2 offspring_prop = 0.5 # 0.4 mutation_rate = 0.01 align_genomes = False pop_size = 8 # ############################################## 32 # Begin simulations record_file = phenome_mode + phenome_format + '_' if phenome_scaling[0] == 1 and phenome_scaling[1] == 1: record_file += 'sca' else: record_file += scaling_mode record_file += str(phenome_scaling[0]) + str( phenome_scaling[1]) + '_act' + str(num_actuation_cycles) if evolve_flag: record_file = 'ev_fit_' + record_file + ( '_rep' + str(repeats) + '_sur' + str(int(100 * survival_prop)) + '_cro' + str(int(100 * offspring_prop)) + '_mut' + str(int(100 * mutation_rate)) + '_rot' + str(int(align_genomes))) if init_gen == 0: with open(join(root, record_file + '.csv'), 'w') as f_out: f_out.write('code,gen,fit\n') # _MA,fit_AM trajectories = [] for gen_num, sim in enumerate([simulation_file_path] * number_of_generations): if evolve_flag: gen_fname = gen_file_prefix + str(phenome_format) + '_' + str( gen_num + init_gen) + '.csv' generation = pd.read_csv(join(root_output_folder, gen_fname), header=None).to_numpy() if gen_num == 0 and randomise_flag: generation = np.zeros((pop_size, int(np.prod(phenome_dims)))) generation = evolve_next_gen( np.arange(0, generation.shape[0], 1), generation, 0, 0, mutation_rate, key2name, np.zeros(generation.shape[0]), phenome_dims, phenome_mode) else: generation = get_genome(rep_seed) # fitnesses = [0 for _ in range(0, generation.shape[0])] fit_vecs = {} for g in range(0, generation.shape[0]): fit_vecs[g] = [] for i in range(0, int(generation.shape[0] / phenomes_per_sim)): grid_arrangement = np.array([ int(i * phenomes_per_sim + np.floor(j / repeats)) for j in range(0, work_nodes) ]).reshape((grid_dim, grid_dim)) setup_cells.setup_init_cells(init_cells_file_path, generation, grid_arrangement, tuple(phenome_dims), zone_size, corner_offset, key2name, name2dims, phenome_scaling, phenome_mode, scaling_mode) # key_matrix = np.reshape(generation[[i]][:], tuple(phenome_dims)) # [0], dims[1])) # if not key_matrix.sum() == 0: # place_cells(init_cells_file_path, key_matrix, key2name, name2dims) cc3d_caller = CC3DCaller(cc3d_sim_fname=sim, screenshot_output_frequency=0, output_dir=join(root_output_folder, abbrevs[project_name]), result_identifier_tag=i) ret_value = cc3d_caller.run() if track_flag: trajectories.append([ ret_value['result']['trackX'], ret_value['result']['trackY'] ]) fit_vec_grid = calculate_scores(ret_value, fitness_function, zone_size, grid_dim) # for index in set([a for a in grid_arrangement.reshape(-1)]): for x in range(0, fit_vec_grid.shape[0]): for y in range(0, fit_vec_grid.shape[1]): fit_vecs[grid_arrangement[x][y]].append(fit_vec_grid[x][y]) # fitnesses[i] = calculate_scores(ret_value, fitness_function, zone_size, grid_dim) fit_measures, fit_angles = measure_fitness(fit_vecs) # fitnesses = fit_measures.sum(1) fitnesses = fit_measures[:, 0] / num_actuation_cycles if evolve_flag: if not align_genomes: fit_angles = np.zeros(generation.shape[0]) ordered_genomes = np.argsort(-1 * fitnesses) next_gen = evolve_next_gen(ordered_genomes, generation, survival_prop, offspring_prop, mutation_rate, key2name, fit_angles, phenome_dims, phenome_mode) new_gen_fname = gen_file_prefix + str(phenome_format) + '_' + str( gen_num + init_gen + 1) + '.csv' pd.DataFrame(next_gen).to_csv(join(root_output_folder, new_gen_fname), header=False, index=False) with open(join(root, record_file + '.csv'), 'a') as f_out: for i in range(0, generation.shape[0]): gene_code = '' for j in range(0, generation.shape[1]): gene_code += str(int(generation[i, j])) f_out.write(gene_code + ',' + str(gen_num) + ',' + str(fitnesses[i]) + '\n') # + ',' + str(fit_measures[i, 1]) if track_flag: save_trajectories(trajectories, root, traj_label, record_file + '.csv') # plot_trajectories(trajectories, zone_size) winsound.Beep(440, 2000)