Mentions légales du service

Skip to content
Snippets Groups Projects
parameters.py 4.63 KiB
Newer Older
DEBREUVE Eric's avatar
DEBREUVE Eric committed
# Copyright CNRS/Inria/UNS
# Contributor(s): Eric Debreuve (since 2019), Morgane Nadal (2020)
#
# eric.debreuve@cnrs.fr
#
# This software is governed by the CeCILL  license under French law and
# abiding by the rules of distribution of free software.  You can  use,
# modify and/ or redistribute the software under the terms of the CeCILL
# license as circulated by CEA, CNRS and INRIA at the following URL
# "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL license and that you accept its terms.

import ast as asgt
DEBREUVE Eric's avatar
DEBREUVE Eric committed
import configparser
from configparser import DEFAULTSECT as DEFAULT_SECTION
from pathlib import Path as path_t
from typing import Any

from logger_36 import LOGGER, AddFileHandler, LogSystemDetails, SetShowMemoryUsage
from logger_36.main import TimeStamp


_BOOLEANS = (
    ("Connection", "dilatation_erosion"),
    ("Extension", "adapt_hist_equalization"),
    ("Frangi", "bright_on_dark"),
    ("Output", "statistical_analysis"),
    ("Workflow", "in_parallel"),
    ("Workflow", "interactive"),
    ("Workflow", "with_plot"),
)

_INTEGERS = (
    ("Feature", "number_of_bins_curvature"),
    ("Feature", "number_of_bins_length"),
)

_FLOATS = (
    ("Connection", "max_straight_sq_dist"),
    ("Connection", "max_weighted_length"),
    ("Extension", "ext_high"),
    ("Extension", "ext_low"),
    ("Extension", "ext_min_area"),
    ("Extension", "ext_selem_micron"),
    ("Feature", "hist_min_curvature"),
    ("Feature", "hist_min_length"),
    ("Feature", "hist_step_curvature"),
    ("Feature", "hist_step_length"),
    ("Frangi", "alpha"),
    ("Frangi", "beta"),
    ("Frangi", "frangi_c"),
    ("Frangi", "scale_step"),
    ("Soma", "soma_high"),
    ("Soma", "soma_low"),
    ("Soma", "soma_max_area"),
    ("Soma", "soma_min_area"),
    ("Soma", "soma_selem_micron"),
)

_PATHS = (
    ("Input", "data_path"),
    ("Output", "save_csv"),
    ("Output", "save_features_analysis"),
    ("Output", "save_images"),
)

_TO_BE_EVALUATED = (
    ("Feature", "hist_bins_borders_curvature"),
    ("Feature", "hist_bins_borders_length"),
    ("Frangi", "scale_range"),
    ("Input", "voxel_size_in_micron"),
)


def NutrimorphArguments(path: path_t, /) -> tuple[dict[str, Any]]:
DEBREUVE Eric's avatar
DEBREUVE Eric committed
    """"""
    config = configparser.ConfigParser(allow_no_value=True, inline_comment_prefixes="#")
    config.read(path)

    output: dict[str, dict[str, Any]] = dict(
        (_sct, dict(_prm)) for _sct, _prm in config.items() if _sct != DEFAULT_SECTION
    )

    for parameters, getter in (
        (_BOOLEANS, "getboolean"),
        (_INTEGERS, "getint"),
        (_FLOATS, "getfloat"),
        (_PATHS, path_t),
        (_TO_BE_EVALUATED, asgt.literal_eval),
    ):
        if isinstance(getter, str):
            Converted = getattr(config, getter)
        else:
            Converted = lambda _sct, _prm: getter(config.get(_sct, _prm))

        for section, parameter in parameters:
            if output[section][parameter] is not None:
                output[section][parameter] = Converted(section, parameter)

    base_folder = output["Output"]["save_images"] / output["Input"]["data_path"].stem
    if base_folder.exists() and not base_folder.is_dir():
        raise RuntimeError(f"{base_folder}: Exists and is not a folder.")
    if not base_folder.exists():
        base_folder.mkdir(parents=True)
    AddFileHandler(base_folder / f"info-warning-error-{TimeStamp()}.txt")
    SetShowMemoryUsage(True)
    LogSystemDetails()
    LOGGER.info(pprt.pformat(output))

    # Section order: 'Connection', 'Extension', 'Feature', 'Frangi', 'Input', 'Output', 'Soma', 'Workflow'
    return tuple(output[_sct] for _sct in sorted(output.keys()))