Exemple #1
0
 def load_config(self) -> None:
     """ Reload config itself and convert lists in it to sets for the better
         performance.
     """
     try:
         with open(self.i3_cfg_mod_path, "r") as mod_cfg:
             self.cfg = qtoml.load(mod_cfg)
     except FileNotFoundError:
         print(f'file {self.i3_cfg_mod_path} not exists')
Exemple #2
0
def construct_simulation_from_toml(filename: str) -> Simulation:
    """Construct a Simulation instance from a toml input file

    Parameters
    ----------
    filename : `str`
        The name of the file which contains the input specification, in
        `toml` format.

    Returns
    -------
    simulation_instance : `Simulation`
        An instance of the Simulation class, initialized using the data
        in the input file, which was converted into a python dictionary.
    """
    with open(filename) as f:
        input_data = toml.load(f)

    return Simulation(input_data)
Exemple #3
0
def read_sample(sample=None, grayscale=True, **kwargs):
    """ Reads the desired filepaths from disk according to their extensions

    Arguments:
        sample (dict):
        grayscale (bool): wether to read images as grayscale or not (= color)
        kwargs (dict): kwargs are used to overwrite or add to sample

    Returns:
        A dict representing the sample with same keys as sample and the objects loaded
        according to their respective data types

    .. note::

        The following will return the same sample::

            paths = {
                'image': Path('data/dataset/labeled/image/0.png'),
                'depth_xyz': Path('data/dataset/labeled/depth_xyz/0.npz')
            }
            read_sample(paths)

        Or ::

            paths = {
                'image': Path('data/dataset/labeled/image/0.png')
            }
            read_sample(paths, depth_xyz=Path('data/dataset/labeled/depth_xyz/0.npz'))

        Or ::

            im_path = Path('data/dataset/labeled/image/0.png')
            read_sample(paths, image=im_path, depth_xyz=Path('data/dataset/labeled/depth_xyz/0.npz'))
    """
    if sample is None:
        sample = kwargs
    else:
        sample.update(kwargs)
    result = {}
    for part in sample:
        filepath = sample[part]
        part_type = part.split('_')[0]
        if part_type in {"image", "mask"}:
            read_type = cv2.IMREAD_COLOR if (not grayscale) and part_type=="image" else cv2.IMREAD_GRAYSCALE
            img = cv2.imread(str(filepath), read_type)
            result[part] = img
        elif part_type in {"xyz"}:
            read_type = cv2.IMREAD_COLOR
            img = cv2.imread(str(filepath), read_type)
            result[part] = img
        elif part_type in {"pcd"}:
            ppcd = pypcd.PointCloud.from_path(filepath)
            result[part] = pypcd2xyz(ppcd)
        elif part_type in {"depth", "keypoints", "template", "class", "var"}:
            with np.load(filepath) as npz_file:
                result[part] = npz_file.get('arr_0', npz_file.get("test")) # supports only one-array npz files
        elif part_type in {"conf"}:
            with filepath.open() as fp:
                result[part] = toml.load(fp)
        elif part_type in {"kaspardconf"}:
            confparser = ConfigParser()
            confparser.optionxform = lambda option: option # disable lower-casing
            confparser.read(filepath)
            result[part] = {s:dict(confparser.items(s)) for s in confparser.sections()}
            for skey, section in result[part].items():
                for key, item in section.items():
                    try:
                        result[part][skey][key] = float(item)
                    except:
                        pass
        else:
            raise ValueError(f"{part} is either not a valid type or not yet implemented.")
    return result
def _load_toml(filename: str) -> Dict[str, Any]:
    if filename == '-':
        return qtoml.load(sys.stdin)
    with open(filename, 'rt') as file_ptr:
        return qtoml.load(file_ptr)
Exemple #5
0
 def dump_config(self):
     """ Dump current config, can be used for debugging.
     """
     with open(self.mod_cfg_path, "r+") as fp:
         qtoml.dump(self.cfg, fp)
         self.cfg = qtoml.load(fp)
Exemple #6
0
 def load_config(self):
     """ Reload config itself and convert lists in it to sets for the better
         performance.
     """
     with open(self.mod_cfg_path, "r") as fp:
         self.cfg = qtoml.load(fp)
Exemple #7
0
def main():
    import qtoml as toml
    with open('config.toml') as f:
        bot = Bot(config=toml.load(f))
    bot.run()
Exemple #8
0
 def dump_config(self) -> None:
     """ Dump current config, can be used for debugging. """
     with open(self.i3_cfg_mod_path, "r+") as mod_cfg:
         print(self.cfg)
         qtoml.dump(self.cfg, mod_cfg)
         self.cfg = qtoml.load(mod_cfg)
Exemple #9
0
def load_config(path):
    with open(path, 'r') as f:
        config = toml.load(f)
        return config
def read_toml(path):
    f = open(path, 'r')
    data = qtoml.load(f)
    f.close()
    return data
Exemple #11
0
def main(argv=None):
    if os.getpid() == 0 or os.getgid() == 0:
        print("error: asv-bwrap should not be run as root", file=sys.stderr)
        sys.exit(1)

    parser = argparse.ArgumentParser(usage=__doc__.strip())
    parser.add_argument("config_file",
                        metavar="config.toml",
                        help="Configuration file to use.")
    parser.add_argument(
        "command",
        nargs=argparse.REMAINDER,
        metavar="ASV_RUN_ARGS",
        help="Arguments passed to the sandbox script",
    )
    parser.add_argument(
        "--sample-config",
        action=PrintSampleConfig,
        help="Print a sample configuration file to stdout.",
    )
    parser.add_argument(
        "--print-scripts",
        action=PrintScripts,
        help="Print bundled shell script files to stdout.",
    )
    parser.add_argument("--upload",
                        action="store_true",
                        help="After running, upload results.")
    parser.add_argument("--reset",
                        action="store_true",
                        help="Clear sandbox before running.")
    parser.add_argument("--shell",
                        action="store_true",
                        help="Start shell inside sandbox.")
    parser.add_argument(
        "--lock",
        action="store",
        default=None,
        help="Lock file to use, instead of default.",
    )
    parser.add_argument("--version",
                        action="version",
                        version="asv-bwrap {}".format(__version__))
    args = parser.parse_args(argv)

    try:
        with open(args.config_file, "r") as f:
            config = parse_config(toml.load(f))
    except (ValueError, IOError) as err:
        print("error: in {!r}: {!s}".format(args.config_file, err),
              file=sys.stderr)
        sys.exit(1)

    if args.lock is not None:
        lock_path = abspath(args.lock)
    else:
        lock_path = None

    os.chdir(abspath(dirname(args.config_file)))

    base_dir = config["dir"]

    if not isdir(base_dir):
        os.makedirs(base_dir)

    if lock_path is None:
        lock_path = abspath(join(base_dir, "lock"))

    with save_terminal():
        with filelock.FileLock(lock_path, timeout=0):
            do_run(
                args.command,
                config,
                upload=args.upload,
                reset=args.reset,
                shell=args.shell,
            )
            sys.exit(0)