def train_behavioural_bn(bn: OpenBooleanNetwork) -> (OpenBooleanNetwork, VNSOutput): spawn_points = GLOBALS.generate_spawn_points() terminal_nodes = get_terminal_nodes(bn) to_never_flip = set(map(hash, bn.input_nodes + terminal_nodes)) train_scores_cmp = GLOBALS.eval_cmp_function train_eval_fn = lambda bn, ct: pt_evaluation_for_train(bn, ct, spawn_points) train_scramble_strategy = lambda bn, nf, e: bn_scramble_strategy(bn, nf, e.union(to_never_flip)) train_tidy_strategy = edit_boolean_network pvns = VNS( sol_evaluator=train_eval_fn, sols_comparator=train_scores_cmp, sol_scrambler=train_scramble_strategy, sol_tidier=train_tidy_strategy ) params = VNSParameters( target_score=flat((GLOBALS.sd_target_score, float('+inf')), to=tuple), min_flips=GLOBALS.sd_min_flips, max_flips=sum(2**n.arity for n in bn.nodes if hash(n.label) not in to_never_flip), max_iters=GLOBALS.sd_max_iters, max_stalls=GLOBALS.sd_max_stalls, max_stagnation=GLOBALS.sd_max_stagnation ) return pvns(bn, params)
def pt_evaluation_for_test(bn: OpenBooleanNetwork, test_params: Iterable): ''' Run a simulation for each set of test parameters. ''' data = [] for tp in test_params: ### Generate ad hoc configuration for simulation purposes only ################################ simconfig = GLOBALS.generate_sim_config() ### Generate simulation world file for simulation purposes only ################################ if not simconfig.webots_world_path.exists(): logger.info('Generated webots world file from template...') stub_utils.generate_webots_worldfile( GLOBALS.webots_world_path, simconfig.webots_world_path, simconfig.arena_params ) # May be launched parallel (... ?) data.append( evaluate_pt_bncontroller(simconfig, bn, tp) ) return tuple(list(e) for e in zip(*data))
def test_bncontrollers(bns: dict): ''' Test each BN in the collection on the same set of points. Return the collected evaluation data for each test. ''' spawn_points = GLOBALS.generate_spawn_points() data = dict() for k in bns: logger.info(f"Boolean Network {k}") test_params = generate_test_params(spawn_points) data[k] = test_bncontroller(bns[k], test_params) return data
from bncontroller.sim.utils import GLOBALS, load_global_config from bncontroller.filelib.utils import get_dir, FROZEN_DATE from bncontroller.stubs.selector.utils import template_selector_generator from bncontroller.stubs.selector.generation import generate_consistent_bnselector as generate_consistent_bnselector if __name__ == "__main__": load_global_config() N, K, P, I, O = GLOBALS.bn_n, GLOBALS.bn_k, GLOBALS.bn_p, GLOBALS.bn_n_inputs, GLOBALS.bn_n_outputs path = get_dir(Path(GLOBALS.bn_model_path), create_if_dir=True) for l in range(GLOBALS.sd_max_iters): bn = GLOBALS.app_core_function() Path(path / f'{l}_bn_n{N}_k{K}_p{int(P*100)}_{FROZEN_DATE}.ebnf').write_text( bn.to_ebnf()) Path(path / f'{l}_bn_n{N}_k{K}_p{int(P*100)}_{FROZEN_DATE}.json').write_text( bn.to_json()) df = DataFrame(bn.atm.dtableau) df.to_csv(str(path / f'{l}_atm_{FROZEN_DATE}.csv')) exit(1)
date=FROZEN_DATE, )) ### BN Generation / Loading #################################################### bn = generate_or_load_bn(params=GLOBALS.bn_params, path=GLOBALS.bn_model_path, save_virgin=True) ### Launch search algorithm ############################################## if not GLOBALS.train_generate_only: t = time.perf_counter() bn, ctx = GLOBALS.app_core_function(bn) logger.info(f"Search time: {time.perf_counter() - t}s") logger.info(ctx) savepath = GLOBALS.bn_model_path / 'behavioural_bn_{date}.json'.format( mode=GLOBALS.app['mode'], date=FROZEN_DATE) write_json(bn, savepath) logger.info(f'Output model saved to {savepath}.') logger.info('Closing...') logger.flush()
key=GLOBALS.app['mode'], date=futils.FROZEN_DATE, )) ### Load Test Model(s) from Template paths #################################### files, bns = collect_bn_models(GLOBALS.bn_model_path) ### Test ###################################################################### t = time.perf_counter() for i in range(GLOBALS.test_n_instances): logger.info(f'Test instance n°{i}') instance_data = GLOBALS.app_core_function(bns) for k, test_data in instance_data.items(): name = futils.gen_fname( futils.get_simple_fname(files[k].name, futils.FNAME_PATTERN, uniqueness=2), template='rtest_data_{name}' + f'_in{i}.json', ) test_data.to_json(GLOBALS.test_data_path / name, default_handler=jsonrepr) logger.info( f'Test data saved into {str(GLOBALS.test_data_path / name)}')
GLOBALS.bn_params = N, K, P, Q, I, O if not isinstance(tTau, dict): GLOBALS.slct_target_transition_tau = { "a0": {"a0": tTau, "a1": tTau}, "a1": {"a0": tTau, "a1": tTau} } GLOBALS.slct_noise_rho = nRho GLOBALS.slct_target_n_attractors = aN GLOBALS.slct_input_steps_phi = iPhi t = time.perf_counter() bn = GLOBALS.app_core_function(mapper) logger.info(time.perf_counter() - t) while bn is None or not bn.attractors_input_map or None in bn.attractors_input_map: logger.info('Failure. Retrying...') t = time.perf_counter() bn = GLOBALS.app_core_function() logger.info(time.perf_counter() - t) logger.info(dict(**bn.attractors_input_map)) logger.info(dict(**bn.atm.dtableau)) logger.info(dict(**bn.atm.dattractors)) path = FOLDER / f'selective_bn_{iso8106(ms=3)}.json'
from bncontroller.boolnet.structures import OpenBooleanNetwork from bncontroller.rtest import find_bn_type if __name__ == "__main__": load_global_config() if isinstance(GLOBALS.bn_model_path, list) or GLOBALS.bn_model_path.is_dir(): raise Exception('Model path should be a file.') GLOBALS.app['mode'] = 'handcheck' bn = find_bn_type(read_json(GLOBALS.bn_model_path)) config = GLOBALS.generate_sim_config() ### Generate simulation world file for training ################################ stub_utils.generate_webots_worldfile(GLOBALS.webots_world_path, config.webots_world_path, config.arena_params) stub_utils.generate_webots_props_file(GLOBALS.webots_world_path, config.webots_world_path) try: proc_closure = stub_utils.run_simulation(config, bn) except Exception: pass stub_utils.clean_dir(