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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
"""HADDOCK3 modules."""

import re

from abc import ABC, abstractmethod
from contextlib import contextmanager, suppress
from copy import deepcopy
from functools import partial
from os import linesep
from pathlib import Path

from haddock import EmptyPath, log, modules_defaults_path
from haddock.core.defaults import MODULE_IO_FILE, INTERACTIVE_RE_SUFFIX
from haddock.core.exceptions import ConfigurationError
from haddock.core.typing import (
    Any,
    Container,
    FilePath,
    Generator,
    Literal,
    Optional,
    ParamDict,
    Union,
)
from haddock.gear import config
from haddock.gear.clean_steps import clean_output
from haddock.gear.known_cns_errors import find_all_cns_errors
from haddock.gear.parameters import config_mandatory_general_parameters
from haddock.gear.yaml2cfg import read_from_yaml_config, find_incompatible_parameters
from haddock.libs.libhpc import HPCScheduler
from haddock.libs.libgrid import GRIDScheduler, ping_dirac
from haddock.libs.libio import folder_exists, working_directory
from haddock.libs.libmpi import MPIScheduler
from haddock.libs.libontology import ModuleIO, PDBFile
from haddock.libs.libparallel import Scheduler
from haddock.libs.libtimer import log_time
from haddock.libs.libutil import recursive_dict_update


modules_folder = Path(__file__).resolve().parent

_folder_match_regex = "[a-zA-Z]*/"
modules_category = {
    module.name: category.name
    for category in modules_folder.glob(_folder_match_regex)
    for module in category.glob(_folder_match_regex)
}
"""Indexes each module in its specific category. Keys are Paths to the module,
values are their categories. Categories are the modules parent folders."""

modules_names = set(modules_category.keys())

category_hierarchy = [
    "topology",
    "sampling",
    "refinement",
    "scoring",
    "analysis",
    "extras",
]

# this dictionary defines non-mandatory general parameters that can be defined
# as global parameters thus affect all modules, or, instead, can be defined per
# module where the module definition overwrites global definition. Not all
# modules will use these parameters. It is the responsibility of the module to
# extract the parameters it needs.
# the config file is in modules/defaults.cfg
non_mandatory_general_parameters_defaults = read_from_yaml_config(modules_defaults_path)  # noqa : E501

incompatible_defaults_params = find_incompatible_parameters(modules_defaults_path)

config_readers = {
    ".yaml": read_from_yaml_config,
    # module params are internally generated as a mix of toml and cfg format
    # set strict to false
    ".cfg": partial(config.load, strict=False),
}

_step_folder_regex = tuple(
    r"[0-9]+_" + mod_name for mod_name in modules_category.keys()
)
step_folder_regex = "(" + "|".join(_step_folder_regex) + ")"
"""
String for regular expression to match module folders in a run directory.

It will match folders with a numeric prefix followed by underscore ("_")
followed by the name of a module.

Example: https://regex101.com/r/roHls9/1
"""

step_folder_regex_re = re.compile(step_folder_regex)
"""
Compiled regular expression from :py:const:`step_folder_regex`.

It will match folders with a numeric prefix followed by underscore ("_")
followed by the name of a module.

Example: https://regex101.com/r/roHls9/1
"""


@contextmanager
def _not_valid_config() -> Generator[None, None, None]:
    try:
        yield
    except KeyError as err:
        emsg = (
            "The configuration file extension is not supported. "
            f"Supported types are {', '.join(config_readers.keys())}."
        )
        raise ConfigurationError(emsg) from err


class BaseHaddockModule(ABC):
    """HADDOCK3 module's base class."""

    name: str

    def __init__(self, order: int, path: Path, params_fname: FilePath) -> None:
        """
        HADDOCK3 modules base class.

        Parameters
        ----------
        params : dict or path to HADDOCK3 configuration file
            A dictionary or a path to a HADDOCK3 configuration file
            containing the initial module parameters. Usually this is
            defined by the default params.
        """
        self.order = order
        self.path = path
        self.previous_io = self._load_previous_io()

        # instantiate module's parameters
        self._origignal_config_file = params_fname
        with _not_valid_config():
            extension = Path(params_fname).suffix
            self._original_params = config_readers[extension](params_fname)

        self._params: ParamDict = {}
        self.update_params(update_from_cfg_file=params_fname)

        # Some modules might need to overwrite parameters defined by the user
        # This can be done via `_output_params` - whatever the module adds to this
        # variable, will be propagated down to other modules.
        # For example: `topoaa` needs to pass `ligand_param_fname` to `rigidbody` module
        #  so somewhere in the `topoaa` module we need to set: `self._output_params[VALUE] = VAR`
        # IMPORANT: This will be propagated to ALL modules and can have unexpected effects
        self._output_params: dict = {}

    @property
    def params(self) -> ParamDict:
        """Configuration parameters."""  # noqa: D401
        return self._params

    def reset_params(self) -> None:
        """Reset parameters to the ones used to instantiate the class."""
        self._params.clear()
        self.update_params(**self._original_params)

    def update_params(
        self,
        update_from_cfg_file: Optional[FilePath] = None,
        **params: Any,
    ) -> None:
        """
        Update the modules parameters.

        Add/update to the current modules parameters the ones given in
        the function call. If you want to enterily replace the modules
        parameters to their default values use the `reset_params()`
        method.

        Update takes places recursively, that is, nested dictionaries
        will be updated accordingly.

        To update the current config with the parameters defined in an
        HADDOCK3 configuration file use the `update_from_cfg_file`
        parameter.

        To update from a JSON file, first load the JSON into a
        dictionary and unpack the dictionary to the function call.

        Examples
        --------
        >>> m.update_params(param1=value1, param2=value2)

        >>> m.update_params(**param_dict)

        >>> m.update_params(update_from_cfg_file=path_to_file)

        # if you wish to start from scratch
        >>> m.reset_params()
        >>> m.update_params(...)
        """
        if update_from_cfg_file and params:
            _msg = "You can not provide both `update_from_cfg_file` and key arguments."
            raise TypeError(_msg)

        if update_from_cfg_file:
            with _not_valid_config():
                extension = Path(update_from_cfg_file).suffix
                params = config_readers[extension](update_from_cfg_file)

        # the updating order is relevant
        _n = recursive_dict_update(
            non_mandatory_general_parameters_defaults, self._params
        )
        self._params = recursive_dict_update(_n, params)
        self._fill_emptypaths()
        self._confirm_fnames_exist()

    def save_config(self, path: FilePath) -> None:
        """Save current parameters to a HADDOCK3 config file."""
        # creates this dictionary for the config to have the module name
        # key in brackets, for example:
        #
        # [topoaa]
        # ...
        ignore = config_mandatory_general_parameters.union(
            non_mandatory_general_parameters_defaults
        )  # noqa: 501
        params = deepcopy(self.params)

        with suppress(KeyError):
            for key in list(ignore):
                params.pop(key)

        config.save({self.name: params}, path)

    def add_parent_to_paths(self) -> None:
        """Add parent path to paths."""
        # convert paths to relative by appending parent
        for key, value in self.params.items():
            if value and key.endswith("_fname"):
                if not Path(value).is_absolute():
                    self.params[key] = Path("..", value)
        return

    @abstractmethod
    def _run(self) -> None: ...

    def run(self, **params: Any) -> None:
        """Execute the module."""
        log.info(f"Running [{self.name}] module")

        self.update_params(**params)
        self.add_parent_to_paths()

        with working_directory(self.path):
            self._run()

        log.info(f"Module [{self.name}] finished.")

    def clean_output(self) -> None:
        """
        Clean module output folder.

        See Also
        --------
        :py:func:`haddock.gear.clean_steps.clean_output`
        """
        with log_time("cleaning output files took"):
            clean_output(self.path, self.params["ncores"])

    @classmethod
    @abstractmethod
    def confirm_installation(cls) -> None:
        """
        Confirm the third-party software needed for the module is installed.

        HADDOCK3's own modules should just return.
        """
        return

    def export_io_models(self, faulty_tolerance: float = 0.0) -> None:
        """
        Export input/output to the ModuleIO interface.

        Modules that do not perform any operation on PDB files should have
         input = output.

        This function implements a common interface for all modules.

        Parameters
        ----------
        faulty_tolerance : int, default 0
            The percentage of missing output allowed. If 20 is given,
            raises an error if 20% of the expected output is missing (not
            saved to disk).
        """
        self.output_models: Union[list[PDBFile], dict[int, PDBFile]]
        assert self.output_models, "`self.output_models` cannot be empty."
        io = ModuleIO()
        # add the input models
        io.add(self.previous_io.output, "i")
        # add the output models
        io.add(self.output_models, "o")
        # Removes un-generated outputs and compute percentage of ungenerated
        faulty = io.check_faulty()
        # Save outputs
        io.save()
        # Check if number of generated outputs is under the tolerance threshold
        if faulty > faulty_tolerance:
            _msg = (
                f"{faulty:.2f}% of output was not generated for this module "
                f"and tolerance was set to {faulty_tolerance:.2f}%."
            )
            # Try to detect CNS errors
            if detected_errors := find_all_cns_errors(self.path):
                _msg += linesep
                for error in detected_errors.values():
                    _msg += f"{str(error['error'])}{linesep}"
            # Show final error message
            self.finish_with_error(_msg)

    def finish_with_error(self, reason: object = "Module has failed.") -> None:
        """Finish with error message."""
        if isinstance(reason, Exception):
            raise RuntimeError("Module has failed.") from reason

        else:
            raise RuntimeError(reason)

    def _load_previous_io(
        self,
        filename: FilePath = MODULE_IO_FILE,
    ) -> ModuleIO:
        if self.order == 0:
            self._num_of_input_molecules = 0
            return ModuleIO()

        io = ModuleIO()
        previous_io = Path(self.previous_path(), filename)

        if previous_io.is_file():
            io.load(previous_io)

        self._num_of_input_molecules = len(io.output)

        return io

    def previous_path(self) -> Path:
        """Give the path from the previous calculation."""
        previous = get_module_steps_folders(self.path.resolve().parent)

        try:
            # return Path(previous[self.order - 1])
            return self.last_step_folder(previous, self.order - 1)
        except IndexError:
            return self.path

    @staticmethod
    def last_step_folder(folders, index):
        """Retrieve last step folder."""
        with_ind = [folder for folder in folders if int(folder.split("_")[0]) == index]
        nb_with_ind = len(with_ind)
        # No matching index
        if nb_with_ind == 0:
            raise IndexError
        # Only one matching index
        elif nb_with_ind == 1:
            return with_ind[0]
        # Case of multiple matching index
        else:
            for folder in with_ind:
                if folder.split("_")[-1] != INTERACTIVE_RE_SUFFIX:
                    return folder
            return with_ind[0]

    def log(self, msg: str, level: str = "info") -> None:
        """
        Log a message with a common header.

        Currently the header is the [MODULE NAME] in square brackets.

        Parameters
        ----------
        msg : str
            The log message.

        level : str
            The level log: 'debug', 'info', ...
            Defaults to 'info'.
        """
        getattr(log, level)(f"[{self.name}] {msg}")

    def _confirm_fnames_exist(self) -> None:
        for param, value in self._params.items():
            if param.endswith("_fname") and value:
                if not Path(value).exists():
                    raise FileNotFoundError(f"File not found: {str(value)!r}")

    def _fill_emptypaths(self) -> None:
        """Fill empty paths."""
        for param, value in list(self._params.items()):
            if param.endswith("_fname") and not value:
                self._params[param] = EmptyPath()


EngineMode = Literal["batch", "local", "mpi", "grid"]


def get_engine(
    mode: str,
    params: dict[Any, Any],
) -> partial[Union[HPCScheduler, Scheduler, MPIScheduler, GRIDScheduler]]:
    """
    Create an engine to run the jobs.

    Parameters
    ----------
    mode : str
        The type of engine to create

    params : dict
        A dictionary containing parameters for the engine.
        `get_engine` will retrieve from `params` only those parameters
        needed and ignore the others.
    """
    # a bit of a factory pattern here
    # this might end up in another module but for now its fine here
    if mode == "batch":
        return partial(  # type: ignore
            HPCScheduler,
            target_queue=params["queue"],
            queue_limit=params["queue_limit"],
            concat=params["concat"],
        )

    elif mode == "local":
        return partial(  # type: ignore
            Scheduler,
            ncores=params["ncores"],
            max_cpus=params["max_cpus"],
        )
    elif mode == "mpi":
        return partial(MPIScheduler, ncores=params["ncores"])  # type: ignore

    elif mode == "grid":
        # `grid` mode should only be used IF the grid is reachable,
        #  if not it should fallback to `local`
        grid_available = ping_dirac()

        if grid_available:
            return partial(GRIDScheduler, params=params)  # type: ignore
        else:
            log.warning("GRID is not available, activating fallback using `mode=local`")
            return partial(  # type: ignore
                Scheduler,
                ncores=params["ncores"],
                max_cpus=params["max_cpus"],
            )

    else:
        available_engines = ("batch", "local", "mpi", "grid")
        raise ValueError(
            f"Scheduler `mode` {mode!r} not recognized. "
            f"Available options are {', '.join(available_engines)}"
        )


def get_module_steps_folders(
    folder: FilePath,
    modules: Optional[Container[int]] = None,
) -> list[str]:
    """
    Return a sorted list of the step folders in a running directory.

    Example
    -------
    Consider the folder structure:

    run_dir/
        0_topoaa/
        1_rigidbody/
        2_caprieval/
        3_bad_module_name/
        data/

    >>> get_module_steps_folders("run_dir")
    >>> ["0_topoaa", "1_rigidbody", "2_caprieval"]

    Parameters
    ----------
    folder : str or Path
        Path to the run directory, or to the folder containing the step
        folders.

    Returns
    -------
    list of str
        List containing strings with the names of the step folders.
    """
    # Make sure the folder exists, otherwise this might throw an error
    if not Path(folder).exists():
        return []
    folders = (p.name for p in Path(folder).iterdir() if p.is_dir())
    steps = sorted(
        (f for f in folders if step_folder_regex_re.search(f)),
        key=lambda x: int(x.split("_")[0]),
    )
    if modules:
        steps = [
            st
            for st in steps
            if all(
                [
                    int(st.split("_")[0]) in modules,
                    st.split("_")[1] in modules_names,
                ]
            )
        ]
    return steps


def is_step_folder(path: FilePath) -> bool:
    """
    Assess whether a folder is a possible step folder.

    The folder is considered a step folder if has a zero or positive
    integer index followed by a name of a module.

    Parameters
    ----------
    path : str or pathlib.Path
        The path to the folder.

    Returns
    -------
    bool
        Whether the folder is a step folder or not.
    """
    path = Path(path)
    folder_exists(path)
    main_folder_name = path.name
    parts = main_folder_name.split("_")
    if len(parts) == 2 and parts[0].isdigit() and parts[1] in modules_category:
        return True
    else:
        return False