diff --git a/src/odatse/_info.py b/src/odatse/_info.py index 03e3663f..6a592581 100644 --- a/src/odatse/_info.py +++ b/src/odatse/_info.py @@ -39,8 +39,10 @@ def __init__(self, d: Optional[MutableMapping] = None): """ Initialize the Info object. - Parameters: - d (Optional[MutableMapping]): A dictionary to initialize the Info object. + Parameters + ---------- + d : MutableMapping (optional) + A dictionary to initialize the Info object. """ if d is not None: self.from_dict(d) @@ -51,11 +53,15 @@ def from_dict(self, d: MutableMapping) -> None: """ Initialize the Info object from a dictionary. - Parameters: - d (MutableMapping): A dictionary containing the information to initialize the Info object. + Parameters + ---------- + d : MutableMapping + A dictionary containing the information to initialize the Info object. - Raises: - exception.InputError: If any required section is missing in the input dictionary. + Raises + ------ + exception.InputError + If any required section is missing in the input dictionary. """ for section in ["base", "algorithm", "solver"]: if section not in d: @@ -92,16 +98,24 @@ def from_file(cls, file_name, fmt="", **kwargs): """ Create an Info object from a file. - Parameters: - file_name (str): The name of the file to load the information from. - fmt (str): The format of the file (default is ""). - **kwargs: Additional keyword arguments. - - Returns: - Info: An Info object initialized with the data from the file. - - Raises: - ValueError: If the file format is unsupported. + Parameters + ---------- + file_name : str + The name of the file to load the information from. + fmt : str + The format of the file (default is ""). + **kwargs + Additional keyword arguments. + + Returns + ------- + Info + An Info object initialized with the data from the file. + + Raises + ------ + ValueError + If the file format is unsupported. """ if fmt == "toml" or fnmatch(file_name.lower(), "*.toml"): inp = {} @@ -111,4 +125,4 @@ def from_file(cls, file_name, fmt="", **kwargs): inp = mpi.comm().bcast(inp, root=0) return cls(inp) else: - raise ValueError("unsupported file format: {}".format(file_name)) \ No newline at end of file + raise ValueError("unsupported file format: {}".format(file_name)) diff --git a/src/odatse/_main.py b/src/odatse/_main.py index 0bb62619..3efac34b 100644 --- a/src/odatse/_main.py +++ b/src/odatse/_main.py @@ -23,9 +23,9 @@ def main(): """ - Main function to run the data-analysis software for quantum beam diffraction experiments - on 2D material structures. It parses command-line arguments, loads the input file, - selects the appropriate algorithm and solver, and executes the analysis. + Main function to run the data-analysis software for quantum beam diffraction experiments + on 2D material structures. It parses command-line arguments, loads the input file, + selects the appropriate algorithm and solver, and executes the analysis. """ import argparse diff --git a/src/odatse/algorithm/_algorithm.py b/src/odatse/algorithm/_algorithm.py index 5f8ce014..76db1470 100644 --- a/src/odatse/algorithm/_algorithm.py +++ b/src/odatse/algorithm/_algorithm.py @@ -76,9 +76,14 @@ def __init__( """ Initialize the algorithm with the given information and runner. - :param info: Information object containing algorithm and base parameters. - :param runner: Optional runner object to execute the algorithm. - :param run_mode: Mode in which the algorithm should run. + Parameters + ---------- + info : Info + Information object containing algorithm and base parameters. + runner : Runner (optional) + Optional runner object to execute the algorithm. + run_mode : str + Mode in which the algorithm should run. """ self.mpicomm = mpi.comm() self.mpisize = mpi.size() @@ -132,7 +137,10 @@ def __init_rng(self, info: odatse.Info) -> None: """ Initialize the random number generator. - :param info: Information object containing algorithm parameters. + Parameters + ---------- + info : Info + Information object containing algorithm parameters. """ seed = info.algorithm.get("seed", None) seed_delta = info.algorithm.get("seed_delta", 314159) @@ -146,7 +154,10 @@ def set_runner(self, runner: odatse.Runner) -> None: """ Set the runner for the algorithm. - :param runner: Runner object to execute the algorithm. + Parameters + ---------- + runner : Runner + Runner object to execute the algorithm. """ self.runner = runner @@ -189,7 +200,10 @@ def post(self) -> Dict: """ Perform post-processing after the algorithm has run. - :return: Dictionary containing post-processing results. + Returns + ------- + Dict + Dictionary containing post-processing results. """ if self.status < AlgorithmStatus.RUN: msg = "algorithm has not run yet" @@ -237,7 +251,10 @@ def write_timer(self, filename: Path): """ Write the timing information to a file. - :param filename: Path to the file where timing information will be written. + Parameters + ---------- + filename : Path + Path to the file where timing information will be written. """ with open(filename, "w") as fw: fw.write("#in units of seconds\n") @@ -259,9 +276,14 @@ def _save_data(self, data, filename="state.pickle", ngen=3) -> None: """ Save data to a file with versioning. - :param data: Data to be saved. - :param filename: Name of the file to save the data. - :param ngen: Number of generations for versioning. + Parameters + ---------- + data + Data to be saved. + filename + Name of the file to save the data. + ngen : int, default: 3 + Number of generations for versioning. """ try: fn = Path(filename + ".tmp") @@ -287,8 +309,15 @@ def _load_data(self, filename="state.pickle") -> Dict: """ Load data from a file. - :param filename: Name of the file to load the data from. - :return: Dictionary containing the loaded data. + Parameters + ---------- + filename + Name of the file to load the data from. + + Returns + ------- + Dict + Dictionary containing the loaded data. """ if Path(filename).exists(): try: @@ -317,7 +346,10 @@ def _check_parameters(self, param=None): """ Check the parameters of the algorithm against previous parameters. - :param param: Previous parameters to check against. + Parameters + ---------- + param (optional) + Previous parameters to check against. """ info = flatten_dict(self.info) info_prev = flatten_dict(param) @@ -335,10 +367,19 @@ def flatten_dict(d, parent_key="", separator="."): """ Flatten a nested dictionary. - :param d: Dictionary to flatten. - :param parent_key: Key for the parent dictionary. - :param separator: Separator to use between keys. - :return: Flattened dictionary. + Parameters + ---------- + d + Dictionary to flatten. + parent_key : str, default : "" + Key for the parent dictionary. + separator : str, default : "." + Separator to use between keys. + + Returns + ------- + dict + Flattened dictionary. """ items = [] if d: @@ -348,4 +389,4 @@ def flatten_dict(d, parent_key="", separator="."): items.extend(flatten_dict(val, key, separator=separator).items()) else: items.append((key, val)) - return dict(items) \ No newline at end of file + return dict(items) diff --git a/src/odatse/algorithm/mapper_mpi.py b/src/odatse/algorithm/mapper_mpi.py index bc0a0022..cc3a8e26 100644 --- a/src/odatse/algorithm/mapper_mpi.py +++ b/src/odatse/algorithm/mapper_mpi.py @@ -40,10 +40,16 @@ def __init__(self, info: odatse.Info, """ Initialize the Algorithm instance. - :param info: Information object containing algorithm parameters. - :param runner: Optional runner object for submitting tasks. - :param domain: Optional domain object, defaults to MeshGrid. - :param run_mode: Mode to run the algorithm, defaults to "initial". + Parameters + ---------- + info : Info + Information object containing algorithm parameters. + runner : Runner + Optional runner object for submitting tasks. + domain : + Optional domain object, defaults to MeshGrid. + run_mode : str + Mode to run the algorithm, defaults to "initial". """ super().__init__(info=info, runner=runner, run_mode=run_mode) @@ -174,7 +180,10 @@ def _post(self) -> Dict: """ Post-process the results and gather data from all MPI ranks. - :return: Dictionary of results. + Returns + ------- + Dict + Dictionary of results. """ if self.mpisize > 1: fx_lists = self.mpicomm.allgather(self.fx_list) @@ -196,7 +205,10 @@ def _save_state(self, filename) -> None: """ Save the current state of the algorithm to a file. - :param filename: The name of the file to save the state to. + Parameters + ---------- + filename + The name of the file to save the state to. """ data = { "mpisize": self.mpisize, @@ -212,8 +224,12 @@ def _load_state(self, filename, restore_rng=True): """ Load the state of the algorithm from a file. - :param filename: The name of the file to load the state from. - :param restore_rng: Whether to restore the random number generator state. + Parameters + ---------- + filename + The name of the file to load the state from. + restore_rng : bool + Whether to restore the random number generator state. """ data = self._load_data(filename) if not data: @@ -230,4 +246,4 @@ def _load_state(self, filename, restore_rng=True): self.fx_list = data["fx_list"] - assert len(self.mesh_list) == data["mesh_size"] \ No newline at end of file + assert len(self.mesh_list) == data["mesh_size"] diff --git a/src/odatse/algorithm/min_search.py b/src/odatse/algorithm/min_search.py index 62bbb399..14e07615 100644 --- a/src/odatse/algorithm/min_search.py +++ b/src/odatse/algorithm/min_search.py @@ -60,10 +60,16 @@ def __init__(self, info: odatse.Info, """ Initialize the Algorithm class. - :param info: Information object containing algorithm settings. - :param runner: Runner object for submitting jobs. - :param domain: Domain object defining the search space. - :param run_mode: Mode of running the algorithm. + Parameters + ---------- + info : Info + Information object containing algorithm settings. + runner : Runner + Runner object for submitting jobs. + domain : + Domain object defining the search space. + run_mode : str + Mode of running the algorithm. """ super().__init__(info=info, runner=runner, run_mode=run_mode) @@ -132,9 +138,17 @@ def _f_calc(x_list: np.ndarray, iset) -> float: """ Calculate the objective function value. - :param x_list: List of variables. - :param iset: Set index. - :return: Objective function value. + Parameters + ---------- + x_list : np.ndarray + List of variables. + iset : + Set index. + + Returns + ------- + float + Objective function value. """ # check if within region -> boundary option in minimize # note: 'bounds' option supported in scipy >= 1.7.0 @@ -259,4 +273,4 @@ def _post(self): for x, y in zip(label_list, x0s[idx]): fp.write(f"initial {x} = {y}\n") - return {"x": xs[idx], "fx": fxs[idx], "x0": x0s[idx]} \ No newline at end of file + return {"x": xs[idx], "fx": fxs[idx], "x0": x0s[idx]} diff --git a/src/odatse/algorithm/montecarlo.py b/src/odatse/algorithm/montecarlo.py index 3a55df63..2248861e 100644 --- a/src/odatse/algorithm/montecarlo.py +++ b/src/odatse/algorithm/montecarlo.py @@ -162,11 +162,11 @@ def __init__(self, info: odatse.Info, def _initialize(self): """ - Initialize the algorithm state. + Initialize the algorithm state. - This method sets up the initial state of the algorithm, including the - positions and energies of the walkers, and resets the counters for - accepted and trial steps. + This method sets up the initial state of the algorithm, including the + positions and energies of the walkers, and resets the counters for + accepted and trial steps. """ if self.iscontinuous: self.domain.initialize(rng=self.rng, limitation=self.runner.limitation, num_walkers=self.nwalkers) @@ -224,20 +224,20 @@ def _setup_neighbour(self, info_param): def _evaluate(self, in_range: np.ndarray = None) -> np.ndarray: """ - Evaluate the current "Energy"s. + Evaluate the current "Energy"s. - This method overwrites `self.fx` with the result. + This method overwrites `self.fx` with the result. - Parameters - ---------- - in_range : np.ndarray, optional - Array indicating whether each walker is within the valid range (default is None). + Parameters + ---------- + in_range : np.ndarray, optional + Array indicating whether each walker is within the valid range (default is None). - Returns - ------- - np.ndarray - Array of evaluated energies for the current configurations. - """ + Returns + ------- + np.ndarray + Array of evaluated energies for the current configurations. + """ # print(">>> _evaluate") for iwalker in range(self.nwalkers): x = self.x[iwalker, :] @@ -254,18 +254,18 @@ def _evaluate(self, in_range: np.ndarray = None) -> np.ndarray: def propose(self, current: np.ndarray) -> np.ndarray: """ - Propose the next candidate positions for the walkers. - - Parameters - ---------- - current : np.ndarray - Current positions of the walkers. - - Returns - ------- - proposed : np.ndarray - Proposed new positions for the walkers. - """ + Propose the next candidate positions for the walkers. + + Parameters + ---------- + current : np.ndarray + Current positions of the walkers. + + Returns + ------- + proposed : np.ndarray + Proposed new positions for the walkers. + """ if self.iscontinuous: dx = self.rng.normal(size=(self.nwalkers, self.dimension)) * self.xstep proposed = current + dx @@ -281,10 +281,11 @@ def local_update( file_result: TextIO, extra_info_to_write: Union[List, Tuple] = None, ): - """one step of Monte Carlo + """ + one step of Monte Carlo Parameters - ========== + ---------- beta: np.ndarray inverse temperature for each walker file_trial: TextIO diff --git a/src/odatse/algorithm/pamc.py b/src/odatse/algorithm/pamc.py index a6918ec1..e2ce9d06 100644 --- a/src/odatse/algorithm/pamc.py +++ b/src/odatse/algorithm/pamc.py @@ -350,15 +350,16 @@ def _run(self) -> None: def _gather_information(self, numT: int = None) -> Dict[str, np.ndarray]: """ - Arguments - --------- + Gather status information of each process - numT: int + Parameters + --------- + numT : int size of dataset Returns ------- - res: Dict[str, np.ndarray] + res : Dict[str, np.ndarray] key-value corresponding is the following - fxs @@ -468,11 +469,11 @@ def _save_stats(self, info: Dict[str, np.ndarray]) -> None: def _resample(self) -> None: """ - Perform the resampling of walkers. + Perform the resampling of walkers. - This method gathers information, saves statistical data, and performs resampling - using either fixed or varied weights. The method ensures that the algorithm - maintains a balanced set of walkers across different temperature steps. + This method gathers information, saves statistical data, and performs resampling + using either fixed or varied weights. The method ensures that the algorithm + maintains a balanced set of walkers across different temperature steps. """ res = self._gather_information() self._save_stats(res) diff --git a/src/odatse/domain/_domain.py b/src/odatse/domain/_domain.py index 347b26c5..73c11f83 100644 --- a/src/odatse/domain/_domain.py +++ b/src/odatse/domain/_domain.py @@ -25,18 +25,25 @@ class DomainBase: """ Base class for domain management in the 2DMAT software. - Attributes: - root_dir (Path): The root directory for the domain. - output_dir (Path): The output directory for the domain. - mpisize (int): The size of the MPI communicator. - mpirank (int): The rank of the MPI process. + Attributes + ---------- + root_dir : Path + The root directory for the domain. + output_dir : Path + The output directory for the domain. + mpisize : int + The size of the MPI communicator. + mpirank : int + The rank of the MPI process. """ def __init__(self, info: odatse.Info = None): """ Initializes the DomainBase instance. - Args: - info (odatse.Info, optional): An instance of odatse.Info containing base directory information. + Parameters + ---------- + info : Info, optional + An instance of odatse.Info containing base directory information. """ if info: self.root_dir = info.base["root_dir"] diff --git a/src/odatse/domain/meshgrid.py b/src/odatse/domain/meshgrid.py index a438093f..922e1487 100644 --- a/src/odatse/domain/meshgrid.py +++ b/src/odatse/domain/meshgrid.py @@ -35,8 +35,12 @@ def __init__(self, info: odatse.Info = None, *, param: Dict[str, Any] = None): """ Initialize the MeshGrid object. - :param info: Information object containing algorithm parameters. - :param param: Dictionary containing parameters for setting up the grid. + Parameters + ---------- + info : Info, optional + Information object containing algorithm parameters. + param : dict, optional + Dictionary containing parameters for setting up the grid. """ super().__init__(info) @@ -65,7 +69,10 @@ def _setup(self, info_param): """ Setup the grid based on provided parameters. - :param info_param: Dictionary containing parameters for setting up the grid. + Parameters + ---------- + info_param + Dictionary containing parameters for setting up the grid. """ if "mesh_path" in info_param: self._setup_from_file(info_param) @@ -78,7 +85,10 @@ def _setup_from_file(self, info_param): """ Setup the grid from a file. - :param info_param: Dictionary containing parameters for setting up the grid. + Parameters + ---------- + info_param + Dictionary containing parameters for setting up the grid. """ if "mesh_path" not in info_param: raise ValueError("ERROR: mesh_path not defined") @@ -110,7 +120,10 @@ def _setup_grid(self, info_param): """ Setup the grid based on min, max, and num lists. - :param info_param: Dictionary containing parameters for setting up the grid. + Parameters + ---------- + info_param + Dictionary containing parameters for setting up the grid. """ if "min_list" not in info_param: raise ValueError("ERROR: algorithm.param.min_list is not defined in the input") @@ -144,8 +157,12 @@ def store_file(self, store_path, *, header=""): """ Store the grid data to a file. - :param store_path: Path to the file where the grid data will be stored. - :param header: Header to be included in the file. + Parameters + ---------- + store_path + Path to the file where the grid data will be stored. + header + Header to be included in the file. """ if self.mpirank == 0: np.savetxt(store_path, [[*v] for idx, *v in self.grid], header=header) @@ -155,8 +172,15 @@ def from_file(cls, mesh_path): """ Create a MeshGrid object from a file. - :param mesh_path: Path to the file containing the grid data. - :return: MeshGrid object. + Parameters + ---------- + mesh_path + Path to the file containing the grid data. + + Returns + ------- + MeshGrid + a MeshGrid object. """ return cls(param={"mesh_path": mesh_path}) @@ -165,8 +189,15 @@ def from_dict(cls, param): """ Create a MeshGrid object from a dictionary of parameters. - :param param: Dictionary containing parameters for setting up the grid. - :return: MeshGrid object. + Parameters + ---------- + param + Dictionary containing parameters for setting up the grid. + + Returns + ------- + MeshGrid + a MeshGrid object. """ return cls(param=param) diff --git a/src/odatse/exception.py b/src/odatse/exception.py index 39a21755..0c83464b 100644 --- a/src/odatse/exception.py +++ b/src/odatse/exception.py @@ -21,11 +21,12 @@ class Error(Exception): class InputError(Error): - """Exception raised for errors in inputs + """ + Exception raised for errors in inputs - Attributes - ========== - message: str + Parameters + ---------- + message : str explanation """ diff --git a/src/odatse/solver/_solver.py b/src/odatse/solver/_solver.py index efaf628a..4a3f41c1 100644 --- a/src/odatse/solver/_solver.py +++ b/src/odatse/solver/_solver.py @@ -47,8 +47,10 @@ def __init__(self, info: odatse.Info) -> None: """ Initialize the solver with the given information. - Args: - info (odatse.Info): Information object containing configuration details. + Parameters + ---------- + info : Info + Information object containing configuration details. """ self.root_dir = info.base["root_dir"] self.output_dir = info.base["output_dir"] @@ -66,8 +68,10 @@ def name(self) -> str: """ Get the name of the solver. - Returns: - str: The name of the solver. + Returns + ------- + str + The name of the solver. """ return self._name @@ -76,13 +80,20 @@ def evaluate(self, x: np.ndarray, arg: Tuple = (), nprocs: int = 1, nthreads: in """ Evaluate the solver with the given parameters. - Args: - x (np.ndarray): Input data array. - arg (Tuple, optional): Additional arguments for evaluation. Defaults to (). - nprocs (int, optional): Number of processes to use. Defaults to 1. - nthreads (int, optional): Number of threads to use. Defaults to 1. + Parameters + ---------- + x : np.ndarray + Input data array. + arg : Tuple, optional + Additional arguments for evaluation. Defaults to (). + nprocs : nt, optional + Number of processes to use. Defaults to 1. + nthreads : int, optional + Number of threads to use. Defaults to 1. - Raises: - NotImplementedError: This method should be implemented by subclasses. + Raises + ------ + NotImplementedError + This method should be implemented by subclasses. """ - raise NotImplementedError() \ No newline at end of file + raise NotImplementedError() diff --git a/src/odatse/util/graph.py b/src/odatse/util/graph.py index ac7a0f48..2cfb9f08 100644 --- a/src/odatse/util/graph.py +++ b/src/odatse/util/graph.py @@ -24,11 +24,15 @@ def is_connected(nnlist: List[List[int]]) -> bool: """ Check if the graph represented by the neighbor list is connected. - Parameters: - nnlist (List[List[int]]): A list of lists where each sublist represents the neighbors of a node. + Parameters + ---------- + nnlist : List[List[int]] + A list of lists where each sublist represents the neighbors of a node. - Returns: - bool: True if the graph is connected, False otherwise. + Returns + ------- + bool + True if the graph is connected, False otherwise. """ nnodes = len(nnlist) visited = np.full(nnodes, False) @@ -49,11 +53,15 @@ def is_bidirectional(nnlist: List[List[int]]) -> bool: """ Check if the graph represented by the neighbor list is bidirectional. - Parameters: - nnlist (List[List[int]]): A list of lists where each sublist represents the neighbors of a node. + Parameters + ---------- + nnlist : List[List[int]] + A list of lists where each sublist represents the neighbors of a node. - Returns: - bool: True if the graph is bidirectional, False otherwise. + Returns + ------- + bool + True if the graph is bidirectional, False otherwise. """ for i in range(len(nnlist)): for j in nnlist[i]: diff --git a/src/odatse/util/limitation.py b/src/odatse/util/limitation.py index 6663dd2d..785643c4 100644 --- a/src/odatse/util/limitation.py +++ b/src/odatse/util/limitation.py @@ -15,7 +15,10 @@ def __init__(self, is_limitary: bool): """ Initialize the limitation. - :param is_limitary: Boolean indicating if the limitation is active. + Parameters + ---------- + is_limitary : bool + Boolean indicating if the limitation is active. """ self.is_limitary = is_limitary @@ -24,8 +27,15 @@ def judge(self, x: np.ndarray) -> bool: """ Abstract method to judge if the limitation is satisfied. - :param x: Input array to be judged. - :return: Boolean indicating if the limitation is satisfied. + Parameters + ---------- + x : np.ndarray + Input array to be judged. + + Returns + ------- + bool + Boolean indicating if the limitation is satisfied. """ raise NotImplementedError @@ -44,8 +54,15 @@ def judge(self, x: np.ndarray) -> bool: """ Always returns True as there is no limitation. - :param x: Input array to be judged. - :return: Always True. + Parameters + ---------- + x : np.ndarray + Input array to be judged. + + Returns + ------- + bool + Always True. """ return True @@ -58,9 +75,14 @@ def __init__(self, a: np.ndarray, b: np.ndarray, is_limitary: bool): """ Initialize the inequality limitation. - :param a: Coefficient matrix. - :param b: Constant vector. - :param is_limitary: Boolean indicating if the limitation is active. + Parameters + ---------- + a : np.ndarray + Coefficient matrix. + b : np.ndarray + Constant vector. + is_limitary : bool + Boolean indicating if the limitation is active. """ super().__init__(is_limitary) if self.is_limitary: @@ -74,8 +96,15 @@ def judge(self, x: np.ndarray) -> bool: """ Judge if the inequality limitation is satisfied. - :param x: Input array to be judged. - :return: Boolean indicating if the limitation is satisfied. + Parameters + ---------- + x : np.ndarray + Input array to be judged. + + Returns + ------- + bool + Boolean indicating if the limitation is satisfied. """ if self.is_limitary: Ax_b = np.dot(self.a, x) + self.b @@ -89,8 +118,15 @@ def from_dict(cls, d): """ Create an Inequality instance from a dictionary. - :param d: Dictionary containing 'co_a' and 'co_b' keys. - :return: Inequality instance. + Parameters + ---------- + d + Dictionary containing 'co_a' and 'co_b' keys. + + Returns + ------- + Inequality + an Inequality instance. """ co_a: np.ndarray = read_matrix(d.get("co_a", [])) co_b: np.ndarray = read_matrix(d.get("co_b", [])) diff --git a/src/odatse/util/logger.py b/src/odatse/util/logger.py index ca173bc4..c7c17409 100644 --- a/src/odatse/util/logger.py +++ b/src/odatse/util/logger.py @@ -57,14 +57,22 @@ def __init__(self, info: Optional[odatse.Info] = None, """ Initialize the Logger. - Parameters: - info (Optional[odatse.Info]): Information object containing logging parameters. - buffer_size (int): Size of the buffer before writing to the log file. - filename (str): Name of the log file. - write_input (bool): Flag to indicate if input should be logged. - write_result (bool): Flag to indicate if result should be logged. - params (Optional[Dict[str,Any]]): Additional parameters for logging. - **rest: Additional keyword arguments. + Parameters + ---------- + info : Info, optional + Information object containing logging parameters. + buffer_size : int + Size of the buffer before writing to the log file. + filename : str + Name of the log file. + write_input : bool + Flag to indicate if input should be logged. + write_result : bool + Flag to indicate if result should be logged. + params : Dict[str,Any]], optional + Additional parameters for logging. + **rest + Additional keyword arguments. """ if info is not None: info_log = info.runner.get("log", {}) @@ -85,8 +93,10 @@ def is_active(self) -> bool: """ Check if logging is active. - Returns: - bool: True if logging is active, False otherwise. + Returns + ------- + bool + True if logging is active, False otherwise. """ return self.buffer_size > 0 @@ -94,8 +104,10 @@ def prepare(self, proc_dir: Path) -> None: """ Prepare the log file for writing. - Parameters: - proc_dir (Path): Directory where the log file will be created. + Parameters + ---------- + proc_dir : Path + Directory where the log file will be created. """ if not self.is_active(): return @@ -118,10 +130,14 @@ def count(self, x: np.ndarray, args, result: float) -> None: """ Log a call with input and result data. - Parameters: - x (np.ndarray): Input data. - args: Additional arguments. - result (float): Result data. + Parameters + ---------- + x : np.ndarray + Input data. + args : + Additional arguments. + result : float + Result data. """ if not self.is_active(): return @@ -155,4 +171,4 @@ def write(self) -> None: with open(self.logfile, "a") as f: for w in self.buffer: f.write(w) - self.buffer.clear() \ No newline at end of file + self.buffer.clear() diff --git a/src/odatse/util/mapping.py b/src/odatse/util/mapping.py index d8cb0719..dfddb14e 100644 --- a/src/odatse/util/mapping.py +++ b/src/odatse/util/mapping.py @@ -36,11 +36,15 @@ def __call__(self, x: np.ndarray) -> np.ndarray: """ Apply the mapping to the input array. - Parameters: - x (np.ndarray): Input array. - - Returns: - np.ndarray: Mapped array. + Parameters + ---------- + x : np.ndarray + Input array. + + Returns + ------- + np.ndarray + Mapped array. """ raise NotImplementedError @@ -57,11 +61,15 @@ def __call__(self, x: np.ndarray) -> np.ndarray: """ Return the input array unchanged. - Parameters: - x (np.ndarray): Input array. + Parameters + ---------- + x : np.ndarray + Input array. - Returns: - np.ndarray: The same input array. + Returns + ------- + np.ndarray + The same input array. """ return x @@ -78,9 +86,12 @@ def __init__(self, A: Optional[np.ndarray] = None, b: Optional[np.ndarray] = Non """ Initialize the affine mapping. - Parameters: - A (Optional[np.ndarray]): Transformation matrix. - b (Optional[np.ndarray]): Translation vector. + Parameters + ---------- + A : np.ndarray, optional + Transformation matrix. + b : np.ndarray, optional + Translation vector. """ # copy arguments self.A = np.array(A) if A is not None else None @@ -101,11 +112,15 @@ def __call__(self, x: np.ndarray) -> np.ndarray: """ Apply the affine mapping to the input array. - Parameters: - x (np.ndarray): Input array. + Parameters + ---------- + x : np.ndarray + Input array. - Returns: - np.ndarray: Mapped array. + Returns + ------- + np.ndarray + Mapped array. """ if self.A is None: ret = copy.copy(x) @@ -121,11 +136,15 @@ def from_dict(cls, d): """ Create an Affine instance from a dictionary. - Parameters: - d (dict): Dictionary containing 'A' and 'b' keys. + Parameters + ---------- + d : dict + Dictionary containing 'A' and 'b' keys. - Returns: - Affine: An instance of the Affine class. + Returns + ------- + Affine + An instance of the Affine class. """ A: Optional[np.ndarray] = read_matrix(d.get("A", [])) b: Optional[np.ndarray] = read_matrix(d.get("b", [])) @@ -149,4 +168,4 @@ def from_dict(cls, d): raise ValueError("shape of A and b mismatch") b = b.reshape(-1) - return cls(A, b) \ No newline at end of file + return cls(A, b) diff --git a/src/odatse/util/neighborlist.py b/src/odatse/util/neighborlist.py index 0a82f9ea..df5abff9 100644 --- a/src/odatse/util/neighborlist.py +++ b/src/odatse/util/neighborlist.py @@ -50,10 +50,14 @@ def __init__(self, mins: np.ndarray, maxs: np.ndarray, cellsize: float): """ Initialize the Cells object. - Parameters: - mins (np.ndarray): The minimum coordinates of the grid. - maxs (np.ndarray): The maximum coordinates of the grid. - cellsize (float): The size of each cell. + Parameters + ---------- + mins : np.ndarray + The minimum coordinates of the grid. + maxs : np.ndarray + The maximum coordinates of the grid. + cellsize : float + The size of each cell. """ self.dimension = len(mins) self.mins = mins @@ -68,11 +72,15 @@ def coord2cellindex(self, x: np.ndarray) -> int: """ Convert coordinates to a cell index. - Parameters: - x (np.ndarray): The coordinates to convert. + Parameters + ---------- + x : np.ndarray + The coordinates to convert. - Returns: - int: The index of the cell. + Returns + ------- + int + The index of the cell. """ return self.cellcoord2cellindex(self.coord2cellcoord(x)) @@ -80,11 +88,15 @@ def coord2cellcoord(self, x: np.ndarray) -> np.ndarray: """ Convert coordinates to cell coordinates. - Parameters: - x (np.ndarray): The coordinates to convert. + Parameters + ---------- + x : np.ndarray + The coordinates to convert. - Returns: - np.ndarray: The cell coordinates. + Returns + ------- + np.ndarray + The cell coordinates. """ return np.floor((x - self.mins) / self.cellsize).astype(np.int64) @@ -92,11 +104,15 @@ def cellcoord2cellindex(self, ns: np.ndarray) -> int: """ Convert cell coordinates to a cell index. - Parameters: - ns (np.ndarray): The cell coordinates to convert. + Parameters + ---------- + ns : np.ndarray + The cell coordinates to convert. - Returns: - int: The index of the cell. + Returns + ------- + int + The index of the cell. """ index = 0 oldN = 1 @@ -110,11 +126,15 @@ def cellindex2cellcoord(self, index: int) -> np.ndarray: """ Convert a cell index to cell coordinates. - Parameters: - index (int): The index of the cell. + Parameters + ---------- + index : int + The index of the cell. - Returns: - np.ndarray: The cell coordinates. + Returns + ------- + np.ndarray + The cell coordinates. """ ns = np.zeros(self.dimension, dtype=np.int64) for d in range(self.dimension): @@ -128,11 +148,15 @@ def out_of_bound(self, ns: np.ndarray) -> bool: """ Check if cell coordinates are out of bounds. - Parameters: - ns (np.ndarray): The cell coordinates to check. + Parameters + ---------- + ns : np.ndarray + The cell coordinates to check. - Returns: - bool: True if out of bounds, False otherwise. + Returns + ------- + bool + True if out of bounds, False otherwise. """ if np.any(ns < 0): return True @@ -144,11 +168,15 @@ def neighborcells(self, index: int) -> List[int]: """ Get the indices of neighboring cells. - Parameters: - index (int): The index of the cell. + Parameters + ---------- + index : int + The index of the cell. - Returns: - List[int]: The indices of the neighboring cells. + Returns + ------- + List[int] + The indices of the neighboring cells. """ neighbors: List[int] = [] center_coord = self.cellindex2cellcoord(index) @@ -170,15 +198,23 @@ def make_neighbor_list_cell( """ Create a neighbor list using cell-based spatial partitioning. - Parameters: - X (np.ndarray): The coordinates of the points. - radius (float): The radius within which neighbors are considered. - allow_selfloop (bool): Whether to allow self-loops in the neighbor list. - show_progress (bool): Whether to show a progress bar. - comm (mpi.Comm, optional): The MPI communicator. - - Returns: - List[List[int]]: The neighbor list. + Parameters + ---------- + X : np.ndarray + The coordinates of the points. + radius : float + The radius within which neighbors are considered. + allow_selfloop : bool + Whether to allow self-loops in the neighbor list. + show_progress : bool + Whether to show a progress bar. + comm : mpi.Comm, optional + The MPI communicator. + + Returns + ------- + List[List[int]] + The neighbor list. """ if comm is None: mpisize = 1 @@ -234,15 +270,23 @@ def make_neighbor_list_naive( """ Create a neighbor list using a naive all-pairs approach. - Parameters: - X (np.ndarray): The coordinates of the points. - radius (float): The radius within which neighbors are considered. - allow_selfloop (bool): Whether to allow self-loops in the neighbor list. - show_progress (bool): Whether to show a progress bar. - comm (mpi.Comm, optional): The MPI communicator. - - Returns: - List[List[int]]: The neighbor list. + Parameters + ---------- + X : np.ndarray) + The coordinates of the points. + radius : float + The radius within which neighbors are considered. + allow_selfloop : bool + Whether to allow self-loops in the neighbor list. + show_progress : bool + Whether to show a progress bar. + comm : mpi.Comm, optional + The MPI communicator. + + Returns + ------- + List[List[int]] + The neighbor list. """ if comm is None: mpisize = 1 @@ -289,16 +333,25 @@ def make_neighbor_list( """ Create a neighbor list for given points. - Parameters: - X (np.ndarray): The coordinates of the points. - radius (float): The radius within which neighbors are considered. - allow_selfloop (bool): Whether to allow self-loops in the neighbor list. - check_allpairs (bool): Whether to use the naive all-pairs approach. - show_progress (bool): Whether to show a progress bar. - comm (mpi.Comm, optional): The MPI communicator. - - Returns: - List[List[int]]: The neighbor list. + Parameters + ---------- + X : np.ndarray + The coordinates of the points. + radius : float + The radius within which neighbors are considered. + allow_selfloop : bool + Whether to allow self-loops in the neighbor list. + check_allpairs : bool + Whether to use the naive all-pairs approach. + show_progress : bool + Whether to show a progress bar. + comm : mpi.Comm, optional + The MPI communicator. + + Returns + ------- + List[List[int]] + The neighbor list. """ if check_allpairs: return make_neighbor_list_naive( @@ -322,12 +375,17 @@ def load_neighbor_list(filename: PathLike, nnodes: int = None) -> List[List[int] """ Load a neighbor list from a file. - Parameters: - filename (PathLike): The path to the file containing the neighbor list. - nnodes (int, optional): The number of nodes. If None, it will be determined from the file. - - Returns: - List[List[int]]: The neighbor list. + Parameters + ---------- + filename : PathLike + The path to the file containing the neighbor list. + nnodes : int, optional + The number of nodes. If None, it will be determined from the file. + + Returns + ------- + List[List[int]] + The neighbor list. """ if nnodes is None: nnodes = 0 @@ -360,11 +418,16 @@ def write_neighbor_list( """ Write the neighbor list to a file. - Parameters: - filename (str): The path to the output file. - nnlist (List[List[int]]): The neighbor list to write. - radius (float, optional): The neighborhood radius. Defaults to None. - unit (np.ndarray, optional): The unit for each coordinate. Defaults to None. + Parameters + ---------- + filename : str + The path to the output file. + nnlist : List[List[int]] + The neighbor list to write. + radius : float, optional + The neighborhood radius. Defaults to None. + unit : np.ndarray, optional + The unit for each coordinate. Defaults to None. """ with open(filename, "w") as f: if radius is not None: diff --git a/src/odatse/util/read_matrix.py b/src/odatse/util/read_matrix.py index 115fd947..302fc10f 100644 --- a/src/odatse/util/read_matrix.py +++ b/src/odatse/util/read_matrix.py @@ -23,14 +23,20 @@ def read_vector(inp: Union[str, List[float]]) -> np.ndarray: """ Converts an input string or list of floats into a numpy array vector. - Parameters: - inp (Union[str, List[float]]): Input data, either as a space-separated string of numbers or a list of floats. + Parameters + ---------- + inp : Union[str, List[float]] + Input data, either as a space-separated string of numbers or a list of floats. - Returns: - np.ndarray: A numpy array representing the vector. + Returns + ------- + np.ndarray + A numpy array representing the vector. - Raises: - RuntimeError: If the input is not a vector. + Raises + ------ + RuntimeError + If the input is not a vector. """ if isinstance(inp, str): vlist = [float(w) for w in inp.split()] @@ -46,14 +52,20 @@ def read_matrix(inp: Union[str, List[List[float]]]) -> np.ndarray: """ Converts an input string or list of lists of floats into a numpy array matrix. - Parameters: - inp (Union[str, List[List[float]]]): Input data, either as a string with rows of space-separated numbers or a list of lists of floats. + Parameters + ---------- + inp : Union[str, List[List[float]]] + Input data, either as a string with rows of space-separated numbers or a list of lists of floats. - Returns: - np.ndarray: A numpy array representing the matrix. + Returns + ------- + np.ndarray + A numpy array representing the matrix. - Raises: - RuntimeError: If the input is not a matrix. + Raises + ------ + RuntimeError + If the input is not a matrix. """ if isinstance(inp, str): Alist: List[List[float]] = [] diff --git a/src/odatse/util/resampling.py b/src/odatse/util/resampling.py index 0a8d1a5d..266c8080 100644 --- a/src/odatse/util/resampling.py +++ b/src/odatse/util/resampling.py @@ -45,7 +45,10 @@ def __init__(self, weights: Iterable): """ Initialize the BinarySearch resampler with the given weights. - :param weights: An iterable of weights. + Parameters + ---------- + weights : Iterable + An iterable of weights. """ self.reset(weights) @@ -53,7 +56,10 @@ def reset(self, weights: Iterable): """ Reset the resampler with new weights. - :param weights: An iterable of weights. + Parameters + ---------- + weights : Iterable + An iterable of weights. """ self.weights_accumulated = list(itertools.accumulate(weights)) self.wmax = self.weights_accumulated[-1] @@ -63,8 +69,15 @@ def sample(self, rs: np.random.RandomState) -> int: """ Sample a single index based on the weights. - :param rs: A random state for generating random numbers. - :return: A single sampled index. + Parameters + ---------- + rs : np.random.RandomState + A random state for generating random numbers. + + Returns + ------- + int + A single sampled index. """ ... @@ -73,9 +86,17 @@ def sample(self, rs: np.random.RandomState, size) -> np.ndarray: """ Sample multiple indices based on the weights. - :param rs: A random state for generating random numbers. - :param size: The number of samples to generate. - :return: An array of sampled indices. + Parameters + ---------- + rs : np.random.RandomState + A random state for generating random numbers. + size : + The number of samples to generate. + + Returns + ------- + np.ndarray + An array of sampled indices. """ ... @@ -83,9 +104,17 @@ def sample(self, rs: np.random.RandomState, size=None) -> Union[int, np.ndarray] """ Sample indices based on the weights. - :param rs: A random state for generating random numbers. - :param size: The number of samples to generate. If None, a single sample is generated. - :return: A single sampled index or an array of sampled indices. + Parameters + ---------- + rs : np.random.RandomState + A random state for generating random numbers. + size : + The number of samples to generate. If None, a single sample is generated. + + Returns + ------- + int or np.ndarray + A single sampled index or an array of sampled indices. """ if size is None: return self._sample(self.wmax * rs.rand()) @@ -96,8 +125,15 @@ def _sample(self, r: float) -> int: """ Perform a binary search to find the index corresponding to the given random number. - :param r: A random number scaled by the maximum weight. - :return: The index corresponding to the random number. + Parameters + ---------- + r : float + A random number scaled by the maximum weight. + + Returns + ------- + int + The index corresponding to the random number. """ return typing.cast(int, np.searchsorted(self.weights_accumulated, r)) @@ -114,7 +150,10 @@ def __init__(self, weights: Iterable): """ Initialize the WalkerTable resampler with the given weights. - :param weights: An iterable of weights. + Parameters + ---------- + weights : Iterable + An iterable of weights. """ self.reset(weights) @@ -122,7 +161,10 @@ def reset(self, weights: Iterable): """ Reset the resampler with new weights. - :param weights: An iterable of weights. + Parameters + ---------- + weights : Iterable + An iterable of weights. """ self.ptable = np.array(weights).astype(np.float64).flatten() self.N = len(self.ptable) @@ -148,8 +190,15 @@ def sample(self, rs: np.random.RandomState) -> int: """ Sample a single index based on the weights. - :param rs: A random state for generating random numbers. - :return: A single sampled index. + Parameters + ---------- + rs : np.random.RandomState + A random state for generating random numbers. + + Returns + ------- + int + A single sampled index. """ ... @@ -158,9 +207,17 @@ def sample(self, rs: np.random.RandomState, size) -> np.ndarray: """ Sample multiple indices based on the weights. - :param rs: A random state for generating random numbers. - :param size: The number of samples to generate. - :return: An array of sampled indices. + Parameters + ---------- + rs : np.random.RandomState + A random state for generating random numbers. + size : + The number of samples to generate. + + Returns + ------- + np.ndarray + An array of sampled indices. """ ... @@ -168,9 +225,17 @@ def sample(self, rs: np.random.RandomState, size=None) -> Union[int, np.ndarray] """ Sample indices based on the weights. - :param rs: A random state for generating random numbers. - :param size: The number of samples to generate. If None, a single sample is generated. - :return: A single sampled index or an array of sampled indices. + Parameters + ---------- + rs : np.random.RandomState + A random state for generating random numbers. + size : + The number of samples to generate. If None, a single sample is generated. + + Returns + ------- + int or np.ndarray + A single sampled index or an array of sampled indices. """ if size is None: r = rs.rand() * self.N @@ -186,8 +251,15 @@ def _sample(self, r: float) -> int: """ Perform a sampling operation based on the given random number. - :param r: A random number scaled by the number of weights. - :return: The index corresponding to the random number. + Parameters + ---------- + r : float + A random number scaled by the number of weights. + + Returns + ------- + int + The index corresponding to the random number. """ i = int(np.floor(r)) p = r - i diff --git a/src/odatse/util/separateT.py b/src/odatse/util/separateT.py index 38e8cf58..6919533c 100644 --- a/src/odatse/util/separateT.py +++ b/src/odatse/util/separateT.py @@ -37,16 +37,20 @@ def separateT( """ Separates and processes temperature data for quantum beam diffraction experiments. - Parameters: - Ts (np.ndarray): Array of temperature values. - nwalkers (int): Number of walkers. - output_dir (PathLike): Directory to store the output files. - comm (Optional[mpi.Comm]): MPI communicator for parallel processing. - use_beta (bool): Flag to determine if beta values are used instead of temperature. - buffer_size (int, optional): Size of the buffer for reading input data. Default is 10000. - - Returns: - None + Parameters + ---------- + Ts : np.ndarray + Array of temperature values. + nwalkers : int + Number of walkers. + output_dir : PathLike + Directory to store the output files. + comm : mpi.Comm, optional + MPI communicator for parallel processing. + use_beta : bool + Flag to determine if beta values are used instead of temperature. + buffer_size : int, optional + Size of the buffer for reading input data. Default is 10000. """ if comm is None: mpisize = 1