Example #1
0
    def dump_data(self, path: str or Path) -> str:
        
        if check_path(path, create_if_file=True) != 0:
            raise Exception(f"Invalid simulation data dump path:\n\t{path}...")

        write_json(vars(self), path)

        self.clear()
Example #2
0
def check_config(config: Config):

    if config.webots_world_path.is_dir():
        raise Exception(
            'Simulation world template should be a file not a dir.')

    elif not futils.check_path(config.test_data_path, create_if_dir=True):
        raise Exception(
            'Test dataset path in configuration file should be a directory.')
Example #3
0
    def __init__(self, ebnf_str: str):

        self.id = hash(ebnf_str)
        # print(ebnf_str)
        self.N = len(list(filter(lambda x: x, ebnf_str.split('\n')[1:])))
        # print(self.N)

        abc = ''.join(random.SystemRandom().choice(string.ascii_uppercase +
                                                   string.digits +
                                                   string.ascii_lowercase)
                      for _ in range(self.N))

        self.DEFAULT_ATM_WS_PATH = Path(
            f'./tmp/atm-workspace_{iso8106()}_{abc}.txt').absolute()

        # print(self.DEFAULT_ATM_WS_PATH)

        check_path(self.DEFAULT_ATM_WS_PATH, create_if_file=True)

        self.DEFAULT_ATM_WS_PATH.write_text(ebnf_str, encoding='UTF-8')

        net = rBoolNet.loadNetwork(str(self.DEFAULT_ATM_WS_PATH))

        # atm_ws_path.unlink()
        atm = rDiffeRenTES.getATM(net, rBoolNet.getAttractors(net))

        # print(atm)

        jATM = json.loads(rJSONlite.toJSON(atm)[0])

        # print(jATM)

        self.tableau, self.attractors = self.__from_parts(
            jATM['ATM'], jATM['attractors']['binary'])

        # if self.DEFAULT_ATM_WS_PATH.exists():
        self.DEFAULT_ATM_WS_PATH.unlink()
Example #4
0
def generate_or_load_bn(params: BNParams, path: Path, save_virgin=False):

    __bn = None

    if check_path(path, create_if_dir=True):

        generator = template_behaviour_generator(*params)

        __bn = generate_rbn(generator.new_obn, force_consistency=True)

        if save_virgin:
            p = path / 'virgin_bn_{date}.json'.format(date=FROZEN_DATE)

            write_json(__bn.to_json(), p)

            logger.info(f'Virgin BN saved to {p}.')

    else:
        __bn = OpenBooleanNetwork.from_json(read_json(path))
        logger.info(f'BN loaded from {path}.')

    return __bn
Example #5
0
        raise Exception('Model path should be a dir or file')
    elif config.webots_world_path.is_dir():
        raise Exception('Simulation world GLOBALS should be a file not a dir.')


####################################################################################

if __name__ == "__main__":

    ### Load Configuration #########################################################

    load_global_config()

    check_config(GLOBALS)

    GLOBALS.app['mode'] = ('generate' if check_path(
        GLOBALS.bn_model_path, create_if_dir=True) else 'enhance')

    ### Init logger ################################################################

    logger.instance = LoggerFactory.filelogger(
        get_dir(GLOBALS.app_output_path, create_if_dir=True) /
        '{key}_{date}.log'.format(
            key=GLOBALS.app['mode'],
            date=FROZEN_DATE,
        ))

    ### BN Generation / Loading ####################################################

    bn = generate_or_load_bn(params=GLOBALS.bn_params,
                             path=GLOBALS.bn_model_path,
                             save_virgin=True)
Example #6
0
def generate_webots_worldfile(template_path: Path, target_path: Path,
                              world_params: ArenaParams):

    if template_path.is_dir() or target_path.is_dir():
        raise Exception('Simuation world path is not a file.')

    check_path(target_path.parent, create_if_dir=True)

    TEMPLATE = r'\s*controllerArgs\s\"(?:{names})=\\\"(.*)\\\"\"\n'

    controller_args_pattern = TEMPLATE.format(names='|'.join(CONFIG_CLI_NAMES))
    floorsize_pattern = r'\s*floorSize\s+(\d+\s\d+)\n'
    floorradius_pattern = r'\s*radius\s+(\d+)\n'
    controller_pattern = r'\s*controller\s+\"(\w*)\"\n'

    controller_args_sub_value = str(world_params.sim_config).replace('\\', '/')

    size = world_params.floor_size

    if isinstance(size, float):
        floorradius_sub_value = str(size).replace(',', '')
        floorsize_sub_value = str((size, size))[1:-1].replace(',', '')
    else:
        floorradius_sub_value = str(size[0]).replace(',', '')
        floorsize_sub_value = str(size)[1:-1].replace(',', '')

    controller_sub_value = world_params.controller

    text = []

    def sub(x: re.Match, s: str):
        return ''.join([x.string[:x.start(1)], s, x.string[x.end(1):]])

    with open(template_path, 'r') as temp:

        text = temp.readlines()

        epuck_found = False

        for i, line in enumerate(text):

            if "robot" in line.lower():
                epuck_found = False

            if "e-puck" in line.lower():
                epuck_found = True

            text[i] = re.sub(controller_args_pattern,
                             lambda x: sub(x, controller_args_sub_value), line)

            if hash(text[i]) == hash(line):
                text[i] = re.sub(floorsize_pattern,
                                 lambda x: sub(x, floorsize_sub_value), line)

            if hash(text[i]) == hash(line):
                text[i] = re.sub(floorradius_pattern,
                                 lambda x: sub(x, floorradius_sub_value), line)

            if hash(text[i]) == hash(line) and epuck_found:
                text[i] = re.sub(controller_pattern,
                                 lambda x: sub(x, controller_sub_value), line)

    with open(target_path, 'w') as tar:
        tar.write(''.join(text))
Example #7
0
    def generate_sim_config(
            self,
            world_fname='{name}_sim_world_{uniqueness}.{ext}',
            config_fname='{name}_sim_config_{uniqueness}.{ext}',
            data_fname='{name}_sim_data_{uniqueness}.{ext}',
            log_fname='{name}_sim_log_{uniqueness}.{ext}',
            ctrl_fname='{name}_sim_bn_{uniqueness}.{ext}'):
        '''
        Generate a config ready-to-use for running a simulation.
        This method completes or changes the paths of various 
        configuration options involving a path.
        '''

        uniqueness = lambda: FROZEN_DATE

        world_fname = gen_fname(self.app['mode'],
                                template=world_fname,
                                uniqueness=uniqueness,
                                ftype='wbt')

        ctrl_fname = gen_fname(self.app['mode'],
                               template=ctrl_fname,
                               uniqueness=uniqueness,
                               ftype='json')
        config_fname = gen_fname(self.app['mode'],
                                 template=config_fname,
                                 uniqueness=uniqueness,
                                 ftype='json')

        data_fname = gen_fname(
            self.app['mode'],
            template=data_fname,
            uniqueness=uniqueness if self.sim_unique_data_file else iso8106,
            ftype='json')

        log_fname = gen_fname(self.app['mode'],
                              template=log_fname,
                              uniqueness=iso8106,
                              ftype='log')

        # Create Sim Config based on the Experiment Config
        sim_config = Config.from_json(self.to_json())

        sim_config.webots_world_path = get_dir(
            sim_config.webots_world_path, create_if_dir=True) / world_fname

        # get_dir(sim_config.bn_model_path, create_if_dir=True)
        sim_config.bn_model_path = get_dir(Path('./tmp/model').absolute(),
                                           create_if_dir=True) / ctrl_fname

        # get_dir(sim_config.sim_config_path, create_if_dir=True)
        sim_config.sim_config_path = get_dir(Path('./tmp/config').absolute(),
                                             create_if_dir=True) / config_fname

        if check_path(sim_config.sim_data_path) in (1, -2):

            sim_config.sim_data_path = get_dir(
                sim_config.sim_data_path / FROZEN_DATE) / data_fname

        if check_path(sim_config.sim_log_path) in (1, -2):
            sim_config.sim_log_path = get_dir(
                sim_config.sim_log_path / FROZEN_DATE) / log_fname

        return sim_config