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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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
"""General utilities."""

import collections.abc
import contextlib
import os
import platform
import re
import shutil
import subprocess
import sys
from copy import deepcopy
from functools import partial
from importlib.resources import files
from pathlib import Path

import psutil

import haddock
from haddock import EmptyPath, log
from haddock.core.exceptions import SetupError
from haddock.core.typing import (
    PT,
    Any,
    AnyT,
    Callable,
    Container,
    FilePath,
    FilePathT,
    Generator,
    Iterable,
    Optional,
    ParamDict,
    ParamMap,
    ParamMapT,
    Union,
)
from haddock.gear.greetings import get_goodbye_help

check_subprocess = partial(
    subprocess.run,
    shell=True,
    check=True,
    stdout=subprocess.DEVNULL,
)


def get_result_or_same_in_list(
    function: Callable[[PT], AnyT], value: PT
) -> Union[AnyT, list[PT]]:
    """
    Return the result if True or the value within a list.

    Applies `function` to `value` and returns its result if it evaluates
    to True. Otherwise, return the value within a list.

    `function` should receive a single argument, the `value`.
    """
    result = function(value)
    return result if result else [value]


def make_list_if_string(item: Union[str, list[str]]) -> list[str]:
    """Put `item` into a list."""
    if isinstance(item, str):
        return [item]
    return item


def transform_to_list(
    item: Union[Iterable[AnyT], AnyT],
) -> Union[list[AnyT], tuple[AnyT, ...]]:
    """
    Put `item` into a list if not a list already.

    If it is set, transforms the set into a list.

    If it is a dict, returns a list of the keys.

    If it is tuple, returns the tuple.

    If a list, returns the same.

    Everything else returns `item` inside a one element list.
    """
    if isinstance(item, (set, dict)):
        return list(item)

    if isinstance(item, (list, tuple)):
        return item

    return [item]


def copy_files_to_dir(paths: Iterable[FilePath], directory: FilePath) -> None:
    """
    Copy files to directory.

    Parameters
    ----------
    paths : iterable of paths
        Source files.

    directory : path
        Where to copy files to.
    """
    for path in paths:
        shutil.copy(path, directory)


def remove_folder(folder: FilePath) -> None:
    """
    Remove a folder if it exists.

    Parameters
    ----------
    folder : str or Path
        Path to folder to remove.
    """
    if Path(folder).exists():
        log.warning(f"{folder} exists and it will be REMOVED!")
        shutil.rmtree(folder)


def remove_dict_keys(d: ParamMap, keys: Container[str]) -> ParamDict:
    """
    Remove `keys` from dictionary (`d`).

    Return
    ------
    dict
        A copy of `d` dictionary without the `keys`.
    """
    return {k: deepcopy(v) for k, v in d.items() if k not in keys}


def cpu_count() -> int:
    """Count number of available CPU for the process.

    User suggestion, by https://github.com/EricDeveaud

    Note: pid 0 == current process

    FIXME: from python3.13, better to use os.process_cpu_count()

    Returns
    -------
    process_ncores : int
        Number of cores allocated to the process pid.
    """

    def _cpu_count() -> int:
        """Detect number of cores available.

        Returns
        -------
        ncores : int
            Maximum number of cores that can be used.
        """
        try:
            # Try to obtain the number of cpu allocated to the process
            _process_ncores = os.sched_getaffinity(0)
            if isinstance(_process_ncores, set):
                ncores = len(_process_ncores)
            else:
                ncores = int(_process_ncores)
        except AttributeError:
            # If unsucessful, return the number cores detected in the machine
            # Note: this can happen on MacOS, where the os.sched_getaffinity
            # may not be defined/exist.
            ncores = int(os.cpu_count())
        return ncores

    try:
        process_ncores = int(os.process_cpu_count())
    except AttributeError:
        process_ncores = _cpu_count()
    return process_ncores


def parse_ncores(
    n: Optional[Union[int, str]] = None,
    njobs: Optional[int] = None,
    max_cpus: Optional[bool] = None,
) -> int:
    """
    Check the number of cores according to HADDOCK3 architecture.

    Parameters
    ----------
    n : int or str
        The desired number of cores. If `None` is given, returns the
        maximum number of cores allowed, see `max_cpus`.

    njobs : int
        The number of jobs to execute. Optional. The number of cores
        will be compared to `njobs`.

    max_cpus : int
        The maximum number of CPUs allowed. If not specified, defaults
        to the available CPUs minus one.

    Raises
    ------
    SetupError
        If `n` is not positive or not convertable to `int`.

    Returns
    -------
    int
        A correct number of cores according to specifications.
    """
    if max_cpus is None or max_cpus is False:
        max_cpus = max(cpu_count() - 1, 1)  # type: ignore
    if max_cpus is True:
        max_cpus = cpu_count()  # type: ignore
    elif not isinstance(max_cpus, int):
        raise TypeError(f"`max_cpus` not of valid type: {type(max_cpus)}")

    if n is None:
        return max_cpus

    try:
        n = int(n)
    except (TypeError, ValueError) as err:
        _msg = f"`n` must be `int` or `int`-convertable `str`: {n!r} given."
        raise SetupError(_msg) from err

    if n < 1:
        _msg = f"`n` is not positive, this is not possible: {n!r}"
        raise SetupError(_msg)

    if njobs is not None:
        ncores = min(n, njobs, max_cpus)
        log.info(
            f"Selected {ncores} cores to process {njobs} jobs, with {max_cpus} "
            "maximum available cores."
        )
        return ncores

    log.debug(f"`njobs` not specified, evaluating initial value {n}...")
    ncores = min(n, max_cpus)
    log.debug(f"Selected {ncores} for a maximum of {max_cpus} CPUs")
    return ncores


def non_negative_int(
    n: Any,
    exception: type[Exception] = ValueError,
    emsg: str = "`n` do not satisfies",
) -> int:
    """
    Transform `n` in int and returns if `compare` evaluates to True.

    Parameters
    ----------
    n : int-convertable
        Something that can be converted to int.

    exception : Exception
        The Exception to raise in case `n` is not a positive integer.

    emsg : str
        The error message to give to `exception`. May accept formatting
        to pass `n`.

    Raises
    ------
    ValueError, TypeError
        If `n` cannot be converted to `int`
    """
    try:
        n1 = int(n)
        if n1 >= 0:
            return n1
    except Exception as e:
        raise e
    else:
        # don't change to f-strings, .format has a purpose
        raise exception(emsg.format(n))


def recursive_dict_update(d: ParamMapT, u: ParamMap) -> ParamMapT:
    """
    Update dictionary `d` according to `u` recursively.

    https://stackoverflow.com/questions/3232943

    Returns
    -------
    dict
        A new dict object with updated key: values. The original dictionaries
        are not modified.
    """

    def _recurse(d_: ParamMapT, u_: ParamMap) -> ParamMapT:
        for k, v in u_.items():
            if isinstance(v, collections.abc.Mapping):
                d_[k] = _recurse(d_.get(k, {}), v)
            else:
                d_[k] = deepcopy(v)  # in case these are also lists

        return d_

    new = deepcopy(d)
    _recurse(new, u)

    return new


def get_number_from_path_stem(path: FilePath) -> int:
    """
    Extract tail number from path.

    Examples
    --------

        >>> get_number_from_path_stem('src/file_1.pdb')
        >>> 1

        >>> get_number_from_path_stem('src/file_3.pdb')
        >>> 3

        >>> get_number_from_path_stem('file_1231.pdb')
        >>> 1231

        >>> get_number_from_path_stem('src/file11')
        >>> 11

        >>> get_number_from_path_stem('src/file_1234_1.pdb')
        >>> 1

    Parameters
    ----------
    path : str or Path obj
        The path to evaluate.

    Returns
    -------
    int
        The tail integer of the path.
    """
    stem = Path(path).stem
    number = re.findall(r"\d+", stem)[-1]
    return int(number)


def sort_numbered_paths(*paths: FilePathT) -> list[FilePathT]:
    """
    Sort input paths to tail number.

    If possible, sort criteria is provided by
    :py:func:`get_number_from_path_stem`.
    If paths do not have a numbered tag, sort paths alphabetically.

    Parameters
    ----------
    *inputs : str or pathlib.Path
        Paths to files.

    Returns
    -------
    list
        The sorted pathlist. The original types are not modified. If
        strings are given, strings are returns, if Paths are given
        paths are returned.
    """
    try:
        return sorted(paths, key=get_number_from_path_stem)
    except TypeError as err:
        log.exception(err)
        emsg = (
            "Mind the packing *argument, input should be strings or Paths, not a list."
        )
        raise TypeError(emsg)
    except IndexError:
        return sorted(paths, key=lambda x: Path(x).stem)


@contextlib.contextmanager
def log_error_and_exit() -> Generator[None, None, None]:
    """Exit with exception."""
    try:
        yield
    except Exception as err:
        log.exception(err)
        log.error(err)
        log.error(
            "An error has occurred, see log file. And contact the developers if needed."
        )
        log.info(get_goodbye_help())
        sys.exit(1)


def extract_keys_recursive(config: ParamMap) -> Generator[str, None, None]:
    """Extract keys recursively for the needed modules."""
    for param_name, value in config.items():
        if isinstance(value, collections.abc.Mapping):
            yield from extract_keys_recursive(value)
        else:
            yield param_name


def recursive_convert_paths_to_strings(params: ParamMapT) -> ParamMapT:
    """
    Convert paths to strings recursively over a dictionary.

    Parameters
    ----------
    params : dictionary

    Returns
    -------
    dictionary
        A copy of the original dictionary with paths converted to strings.
    """
    params = deepcopy(params)
    for param, value in params.items():
        if isinstance(value, (Path, EmptyPath)):
            params[param] = str(value)
        elif isinstance(value, collections.abc.Mapping):
            params[param] = recursive_convert_paths_to_strings(value)
        elif isinstance(value, (tuple, list)):
            for i, v in enumerate(value):
                if isinstance(v, (Path, EmptyPath)):
                    value[i] = str(v)
            params[param] = value

    return params


def get_arch():
    """Helper function to figure out the architetchure"""
    system = platform.system().lower()
    machine = platform.machine().lower()

    return f"{machine}-{system}"


def get_cns_executable() -> tuple[Path, Path]:
    """
    Locate CNS executable and its Linux variant for grid execution.

    Returns:
        Tuple of (cns_exec, cns_exec_linux) paths

    Raises:
        SystemExit: If CNS executable cannot be found
    """
    cns_exec_dir = Path(files(haddock).joinpath("cns/bin"))  # type: ignore
    arch = get_arch()
    cns_exec = Path(cns_exec_dir, f"{arch}.bin")
    if not cns_exec.exists():
        log.error("CNS executable not found at %s", cns_exec)

        # Fall back to environment variable
        cns_exec_env = os.environ.get("CNS_EXEC")
        if cns_exec_env is None:
            log.error(
                "Please define the CNS binary location by setting the CNS_EXEC "
                "environment variable"
            )
            sys.exit(1)

        cns_exec = Path(cns_exec_env)
        if not cns_exec.exists():
            log.error("CNS executable not found at %s", cns_exec)
            sys.exit(1)

    # Determine Linux-specific executable for grid usage
    cns_exec_linux = Path(cns_exec_dir, "x86_64-linux.bin")

    if not cns_exec_linux.exists():
        log.warning(
            "Current architecture is %s, but grid execution requires "
            "an x86_64-linux binary",
            arch,
        )
        log.warning("Linux CNS binary not found at %s", cns_exec_linux)
        log.warning("GRID mode will not be available")

    return cns_exec, cns_exec_linux


def get_prodrg_exec() -> tuple[Optional[Path], Optional[Path]]:
    """
    Locate the prodrg binary and its parameter file.

    Returns ``(None, None)`` with a warning if the binary cannot be found,
    allowing the application to start normally. The error will surface later
    if ``run_prodrg`` is actually called.

    Returns:
        Tuple of (prodrg_exec, prodrg_param) paths, or (None, None) if not found
    """
    prodrg_dir = Path(files(haddock).joinpath("prodrg"))  # type: ignore
    arch = get_arch()
    prodrg_exec = prodrg_dir / f"prodrg_{arch}"

    if not prodrg_exec.exists():
        prodrg_exec_env = os.environ.get("PRODRG_EXEC")
        if prodrg_exec_env is not None:
            prodrg_exec = Path(prodrg_exec_env)
        else:
            log.warning(
                "prodrg binary not found for arch %s and PRODRG_EXEC is not set. "
                "Automated ligand topology generation will not be available.",
                arch,
            )
            return None, None

    if not prodrg_exec.exists():
        log.warning(
            "prodrg executable not found at %s. "
            "Automated ligand topology generation will not be available.",
            prodrg_exec,
        )
        return None, None

    prodrg_param = prodrg_dir / "prodrg.param"
    if not prodrg_param.exists():
        log.warning(
            "prodrg.param not found at %s. "
            "Automated ligand topology generation will not be available.",
            prodrg_param,
        )
        return None, None

    return prodrg_exec, prodrg_param


def get_available_memory() -> float:
    """
    Get the available system memory in GB.

    Get the available virtual memory in Bytes
    then divide it by (1024 ^ 3) to get this value in GigaBytes

    Returns
    -------
    float
        Available memory in gigabytes (GB).
    """
    return psutil.virtual_memory().available / (1024**3)


def get_necessary_memory(models: list) -> float:
    """
    Estimate the memory required to compute contact maps.

    Calculates memory based on the largest model's estimated atom count.
    The memory estimate assumes a distance matrix of size (atoms x atoms) * 8 bytes.

    Parameters
    ----------
    models : list
        List of model objects with file_name attribute.

    Returns
    -------
    float
        Estimated memory requirement in gigabytes (GB).
    """
    # Compute an approximation of the matrix size
    # Most models will be similar, so just use the first one
    try:
        file_size = os.path.getsize(models[0].file_name)
        estimated_atoms = file_size // 10
    except Exception:
        estimated_atoms = 10000

    if estimated_atoms == 0:
        estimated_atoms = 10000

    matrix_size_bytes = (estimated_atoms * estimated_atoms) * 8
    # Convert it into GigaBytes
    matrix_size_gb = matrix_size_bytes / (1024**3)

    return matrix_size_gb