larvaworld.lib.reg.config ========================= .. py:module:: larvaworld.lib.reg.config .. autoapi-nested-parse:: This module provides classes and functions for managing configurations in the larvaworld package. It includes classes for configuration types and the unique reference type, as well as functions for resetting configurations. Attributes ---------- .. autoapisummary:: larvaworld.lib.reg.config.conf Classes ------- .. autoapisummary:: larvaworld.lib.reg.config.ConfType larvaworld.lib.reg.config.RefType Functions --------- .. autoapisummary:: larvaworld.lib.reg.config.next_idx larvaworld.lib.reg.config.resetConfs Module Contents --------------- .. py:function:: next_idx(id: str, conftype: str = 'Exp') -> int Increment and retrieve the next index for a given configuration type and id. Args: id (str): The id for which the index is to be incremented. conftype (str, optional): The type of configuration. Defaults to 'Exp'. Returns: int: The next index for the given configuration type and id. Raises: IOError: If there is an issue reading or writing the index file. Notes: - The function reads from and writes to a file named 'SimIdx.txt' located in the directory specified by `larvaworld.CONF_DIR`. - If the file does not exist, it initializes a new dictionary with default configuration types. - If the given configuration type or id does not exist in the dictionary, they are initialized. .. py:class:: ConfType(**kwargs: Any) Bases: :py:obj:`param.Parameterized` ConfType is a class that manages different configuration types and their associated dictionaries. It provides methods to load, save, update, and manipulate these configurations. Attributes: conftype (param.Selector): Selector for available configuration types. dict (ClassDict): The configuration dictionary. CONFTYPE_SUBKEYS (util.AttrDict): A dictionary of configuration type subkeys built by the `build_ConfTypeSubkeys` method. .. py:attribute:: conftype .. py:attribute:: dict .. py:attribute:: CONFTYPE_SUBKEYS .. py:method:: build_ConfTypeSubkeys() -> larvaworld.lib.util.AttrDict Constructs a nested dictionary representing configuration subkeys for different configuration types. The method initializes a dictionary with keys from `larvaworld.CONFTYPES` and empty dictionaries as values. It then updates this dictionary with predefined subkey mappings. Returns: util.AttrDict: A dictionary-like object with the combined configuration subkeys. .. py:property:: path_to_dict :type: str Constructs a file path string based on the configuration directory and type. Returns: str: The constructed file path in the format '{larvaworld.CONF_DIR}/{self.conftype}.txt'. .. py:method:: update_dict() -> None Updates the dictionary configuration parameter. This method is triggered when the 'conftype' parameter changes (actually when it is initialized). It updates the item type of the 'dict' parameter to match the 'dict_entry_type' and then reloads the configuration. .. py:method:: getID(id: int | str | list[int | str]) -> larvaworld.lib.util.AttrDict | list[larvaworld.lib.util.AttrDict] Retrieve the configuration stored under an id from the dictionary. If the provided id is a list, the method will recursively retrieve the configuration under each id in the list. Args: id (int, str, or list): The id(s) to retrieve. Can be a single id or a list of ids. Returns: The configuration(s) (nested dictionary(ies)) associated with the provided id(s) from the dictionary. Raises: ValueError: If the provided id does not exist in the dictionary. .. py:method:: get(id: str | list[str]) -> Any | list[Any] Retrieve a generator for a configuration entry by id. If the provided id is a list, recursively retrieve entries for each id in the list. Args: id (Union[str, list]): The id of the configuration entry to retrieve, or a list of ids. Returns: Union[conf_class, list]: A generator for the configuration entry or a list of generators for configuration entries. .. py:method:: load() -> None Loads the dictionary storing the configurations from the specified path and assigns it to the instance variable `dict`. This method reads the dictionary from the file located at `self.path_to_dict`. Raises: FileNotFoundError: If the file at `self.path_to_dict` does not exist. IOError: If there is an error reading the file. .. py:method:: save() -> bool Saves the current state of the dictionary to the specified path. This method saves the dictionary (`self.dict`) to the file located at `self.path_to_dict`. Returns: bool: True if the save operation was successful, False otherwise. .. py:method:: set_dict(d: dict[str, Any]) -> None Sets the dictionary for the configuration type and saves it. Args: d (dict): The dictionary to be set. Returns: None .. py:method:: reset(init: bool = False, recreate: bool = False) -> None Resets the configuration dictionary from the built-in dictionary of predefined configurations. If the configuration dictionary file exists: - If `recreate` is True, removes the persisted file and recreates it from the built-in stored dictionary. - If `init` is True, prints the current number of entries and returns. - If `init` is False, updates the current dictionary with the stored dictionary and prints the updated number of entries. If the configuration dictionary file does not exist: - Initializes the dictionary with the stored dictionary and prints the number of entries. Args: init (bool): Flag to indicate if the reset is for initialization purposes. Defaults to False. recreate (bool): Flag to force recreation of the persisted configuration dictionary from the built-in defaults. .. py:method:: selectIDs(dic: dict[str, Any] = {}) -> larvaworld.lib.util.SuperList Selects and returns a list of ids from the configuration dictionary that match the criteria specified in the given dictionary. Args: dic (dict, optional): A dictionary containing key-value pairs to match against the ids' attributes. Defaults to an empty dictionary. Returns: util.SuperList: A list of ids that match the criteria specified in the dictionary. .. py:method:: setID(id: str, conf: Any, mode: str = 'overwrite') -> None Sets the configuration for a given id. Parameters ---------- id (str): The identifier for the configuration. conf (object): The configuration object to be stored under the id. mode (str, optional): The mode of setting the configuration. It can be 'overwrite' (default) or 'update'. Behavior: - If the id already exists in the dictionary and the mode is 'update', the existing configuration is updated with the new configuration. - Otherwise, the new configuration is set for the given id. - The configuration is saved after setting. - If the configuration type is 'Model', updates related parameters in genetic algorithm selectors and mutators. Side Effects: - Calls the save method to update the dictionary. - Updates genetic algorithm parameters if the configuration type is 'Model'. - Prints a message indicating the configuration has been saved. .. py:method:: delete(id: Optional[str] = None) -> None Delete a configuration entry by its id. Parameters ---------- id (optional): The id of the configuration entry to delete. If not provided, no action is taken. Behavior: - If the provided id exists in the configuration dictionary, the entry is removed. - The updated configuration dictionary is saved. - A message indicating the deletion is printed. .. py:method:: expand(id: Optional[str] = None, conf: Optional[dict[str, Any]] = None) Expands the configuration dictionary by resolving subkeys and their ids. Args: id (str, optional): The identifier for the configuration. Defaults to None. conf (dict, optional): The configuration dictionary to expand. If None, it will be fetched from self.dict using the provided id. Defaults to None. Returns: dict or None: The expanded configuration dictionary if successful, otherwise None. .. py:method:: confID_selector(default: Optional[str] = None, single: bool = True) -> larvaworld.lib.param.OptionalSelector | param.ListSelector A configuration selector object. Parameters ---------- - default: The default configuration id to select (optional). - single (bool): If True, returns an OptionalSelector for a single selection. If False, returns a ListSelector for multiple selections. Returns ------- - OptionalSelector or ListSelector: A selector object for configuration IDs. .. py:property:: reset_func :type: Any Shortcut for the reset configuration function. Returns: function: The stored default configuration function that resets the dictionary for the given configuration type. .. py:property:: stored_dict :type: dict Returns the result of calling the reset_func method. This method is an alias for self.reset_func(). Returns: dict: The dictionary returned by self.reset_func(). .. py:property:: confIDs :type: list[str] Retrieve a sorted list of configuration ids from the configuration dictionary. Returns: list: A sorted list of keys from the configuration dictionary. .. py:property:: conf_class :type: type | None Determines the configuration generator class based on the `conftype` attribute. Returns: class: The configuration generator class corresponding to `conftype`. - If `conftype` is None, returns None. - If `conftype` is found in `reg.gen`, returns the corresponding class from `reg.gen`. - Otherwise, returns `util.AttrDict`. .. py:property:: dict_entry_type :type: type Returns the type of dictionary entry used as a configuration. This method returns the `AttrDict` type, which is a specialized nested dictionary that allows attribute-style access. Returns: type: The `AttrDict` type. .. py:class:: RefType(**kwargs: Any) Bases: :py:obj:`ConfType` RefType class extends ConfType to handle a unique configuration type, the one that accesses the reference datasets' configurations associated with specific ids. .. py:method:: getRefDir(id: str) -> str Get the directory for a given reference id. Parameters ---------- id (str): The id associated with a reference dataset. Returns ------- str: The directory path for the reference dataset. .. py:method:: resolve_ref_dir(dir: str) -> str :staticmethod: Resolve a reference dataset directory. Absolute paths are preserved. Relative registry paths remain rooted in DATA_DIR for compatibility with stored reference dictionaries. .. py:method:: getRef(id: Optional[str] = None, dir: Optional[str] = None) -> dict Get the reference dataset's configuration. Parameters ---------- id (str, optional): The reference id. Defaults to None. dir (str, optional): The directory path. Defaults to None. Returns ------- dict: The reference dataset's configuration. Raises ------ AssertionError: If the reference file does not exist or the configuration does not contain an 'id'. .. py:method:: setRef(c: dict, id: Optional[str] = None, dir: Optional[str] = None) -> None Save the reference dataset's configuration. Parameters ---------- c (dict): The reference dataset's configuration. id (str, optional): The reference id. Defaults to None. dir (str, optional): The directory path. Defaults to None. Raises ------ AssertionError: If the configuration does not contain an 'id'. .. py:method:: path_to_Ref(id: Optional[str] = None, dir: Optional[str] = None) -> str Get the path to the file storing a reference dataset's configuration. Parameters ---------- id (str, optional): The reference id. Defaults to None. dir (str, optional): The directory path. Defaults to None. Returns ------- str: The path to the reference dataset's configuration file. .. py:method:: loadRef(id: Optional[str] = None, dir: Optional[str] = None, load: bool = False, **kwargs: Any) Load a reference dataset. Parameters ---------- id (str, optional): The reference id. Defaults to None. dir (str, optional): The directory path. Defaults to None. load (bool, optional): Whether to load data from the dataset. Defaults to False. **kwargs: Additional keyword arguments for loading the dataset. Returns ------- LarvaDataset: The loaded reference dataset. .. py:method:: loadRefs(ids: Optional[list[str]] = None, dirs: Optional[list[str]] = None, **kwargs: Any) Load multiple reference datasets. Parameters ---------- ids (list, optional): List of reference ids. Defaults to None. dirs (list, optional): List of directory paths. Defaults to None. **kwargs: Additional keyword arguments for loading the datasets. Returns ------- ItemList: A list of loaded reference datasets. .. py:method:: retrieve_dataset(dataset=None, load: bool = True, **kwargs: Any) Retrieve a dataset, loading it if necessary. Parameters ---------- dataset (LarvaDataset, optional): The dataset to retrieve. Defaults to None. load (bool, optional): Whether to load the dataset. Defaults to True. **kwargs: Additional keyword arguments for loading the dataset. Returns ------- LarvaDataset: The retrieved dataset. .. py:method:: cleanRefIDs() -> None Purge reference ids by removing invalid ones. .. py:property:: dict_entry_type :type: type Get the type of dictionary entries. Returns: type: The type of dictionary entries, which is str. .. py:method:: getRefGroups() -> larvaworld.lib.util.AttrDict Get reference groups. Returns: AttrDict: A dictionary of reference groups. .. py:property:: RefGroupIDs :type: list Get the IDs of reference groups. Returns: list: A list of reference group IDs. .. py:property:: Refdict :type: larvaworld.lib.util.AttrDict Get a dictionary of all reference datasets' configurations. Returns: AttrDict: A nested dictionary of all reference datasets' configurations. .. py:method:: getRefGroup(group_id: str) -> larvaworld.lib.util.AttrDict Get a reference group by its ID. Parameters ---------- group_id (str): The group ID. Returns ------- AttrDict: A nested dictionary of all reference datasets' configurations in the group. .. py:method:: loadRefGroup(group_id: str, to_return: str = 'collection', **kwargs: Any) Load a reference group by its ID. Parameters ---------- group_id (str): The group ID. to_return (str, optional): The format to return the group in. Defaults to 'collection'. **kwargs: Additional keyword arguments for loading the references. Returns ------- Union[AttrDict, ItemList, LarvaDatasetCollection]: The loaded reference group. .. py:data:: conf :type: larvaworld.lib.util.AttrDict .. py:function:: resetConfs(conftypes: Optional[list[str]] = None, **kwargs: Any) -> None Resets the configurations for the specified configuration types. Parameters ---------- conftypes (list, optional): A list of configuration types to reset. If None, defaults to larvaworld.CONFTYPES. **kwargs: Additional keyword arguments to pass to the reset method of each configuration type. Returns ------- None