mosna 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mosna/__init__.py ADDED
@@ -0,0 +1,60 @@
1
+ #! /usr/bin/env python3
2
+
3
+ """
4
+ Multi-Omics Spatial Network Analysis
5
+ ====================================
6
+
7
+ Extract clinically relevant features from spatial omics data, using spatial
8
+ networks (``scipy.sparse`` CSR adjacency matrices built with tysserand), and
9
+ train predictive models against clinical outcomes.
10
+
11
+ All public functions are available from the package namespace::
12
+
13
+ import mosna
14
+ mixmat = mosna.mixing_matrix(nodes, A, attributes)
15
+
16
+ ``from mosna import mosna`` still works but is deprecated (``FutureWarning``).
17
+
18
+ Submodules, following the stages of the pipeline:
19
+
20
+ - ``preprocessing``: data transformations, nodes tables, batch correction
21
+ - ``assortativity``: assortativity and mixing matrices, permutation nulls
22
+ - ``nas``: Neighbors Aggregation Statistics and spatial omic features
23
+ - ``niches``: alternative niche methods, dimensionality reduction, clustering
24
+ - ``models``: data cleaning, logistic / stepwise regressions, XGBoost, risk ratios
25
+ - ``survival``: survival thresholds and plots
26
+ - ``plotting``: PCA, heatmaps, distributions, clusters and niches plots
27
+ - ``screening``: screening of NAS / niches parameters against outcomes
28
+ - ``generators``: toy networks with known assortativity
29
+
30
+ Settings: ``mosna.gpu_clustering`` (RAPIDS GPU clustering, detected on first
31
+ use, set it to False to force the CPU path) and ``mosna.WORKER_MEMORY_DEFAULT``
32
+ (memory budget of a parallel worker).
33
+
34
+ Messages are logged with the ``logging`` module (``mosna`` logger, INFO level
35
+ to stdout by default): silence them with
36
+ ``logging.getLogger('mosna').setLevel(logging.WARNING)``.
37
+
38
+ Heavy optional libraries (torch via torchgmm, RAPIDS, umap, hdbscan,
39
+ leidenalg, scanorama, sksurv, xgboost) are imported inside the functions that
40
+ use them: importing all of them costs ~1.4 GB per process, which is paid again
41
+ by every worker process of parallel computations.
42
+ """
43
+
44
+ import sys
45
+
46
+ from . import _logging
47
+ from ._settings import SettingsModule
48
+ from ._utils import renormalize, to_numpy
49
+ from .assortativity import *
50
+ from .generators import *
51
+ from .models import *
52
+ from .nas import *
53
+ from .niches import *
54
+ from .plotting import *
55
+ from .preprocessing import *
56
+ from .screening import *
57
+ from .survival import *
58
+
59
+ sys.modules[__name__].__class__ = SettingsModule
60
+ del sys, SettingsModule
mosna/_gpu.py ADDED
@@ -0,0 +1,34 @@
1
+ """
2
+ Lazy detection of the RAPIDS stack used for GPU clustering.
3
+
4
+ The flag lives in this module; ``mosna.gpu_clustering`` reads and sets it.
5
+ """
6
+
7
+
8
+ def _detect_gpu_clustering():
9
+ """True if the RAPIDS stack used for GPU clustering can be imported."""
10
+ try:
11
+ import cudf # noqa: F401
12
+ from cuml import HDBSCAN # noqa: F401
13
+
14
+ return True
15
+ except Exception:
16
+ return False
17
+
18
+
19
+ def _use_gpu_clustering():
20
+ """
21
+ Value of the module flag ``gpu_clustering``, detected on first use. Set
22
+ ``mosna.gpu_clustering = False`` to force the CPU path.
23
+ """
24
+ flag = globals().get('gpu_clustering')
25
+ if flag is None:
26
+ flag = globals()['gpu_clustering'] = _detect_gpu_clustering()
27
+ return flag
28
+
29
+
30
+ def __getattr__(name):
31
+ # `mosna.gpu_clustering` is detected lazily, as importing RAPIDS is costly
32
+ if name == 'gpu_clustering':
33
+ return _use_gpu_clustering()
34
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
mosna/_logging.py ADDED
@@ -0,0 +1,23 @@
1
+ """
2
+ Logging configuration of mosna.
3
+
4
+ Modules log through ``logging.getLogger(__name__)``, children of the ``mosna``
5
+ logger. Messages of functions run with ``verbose > 0`` are logged at the INFO
6
+ level, problems at the WARNING level. To keep the former ``print`` behavior in
7
+ notebooks and scripts, the ``mosna`` logger writes bare messages to stdout at
8
+ the INFO level, without propagating to the root logger. Silence it with
9
+ ``logging.getLogger('mosna').setLevel(logging.WARNING)``, or route messages to
10
+ your own handlers with ``logging.getLogger('mosna').propagate = True`` after
11
+ removing its handler.
12
+ """
13
+
14
+ import logging
15
+ import sys
16
+
17
+ logger = logging.getLogger('mosna')
18
+ if not logger.handlers:
19
+ _handler = logging.StreamHandler(sys.stdout)
20
+ _handler.setFormatter(logging.Formatter('%(message)s'))
21
+ logger.addHandler(_handler)
22
+ logger.setLevel(logging.INFO)
23
+ logger.propagate = False
mosna/_parallel.py ADDED
@@ -0,0 +1,113 @@
1
+ """
2
+ Parallel computations over networks or permutations (joblib loky), with
3
+ the number of workers capped by CPUs, tasks and available memory.
4
+ """
5
+
6
+ import re
7
+ from multiprocessing import cpu_count
8
+
9
+ import numpy as np
10
+ from joblib import Parallel, delayed
11
+ from tqdm import tqdm
12
+
13
+
14
+ def _available_memory():
15
+ """Memory available for new processes, in bytes."""
16
+ try:
17
+ import psutil
18
+
19
+ return psutil.virtual_memory().available
20
+ except ImportError:
21
+ try:
22
+ with open('/proc/meminfo') as f:
23
+ for line in f:
24
+ if line.startswith('MemAvailable:'):
25
+ return int(line.split()[1]) * 1024
26
+ except OSError:
27
+ pass
28
+ return None
29
+
30
+
31
+ def _parse_memory(memory):
32
+ """Parse a memory size given as bytes or as a string like '4GB', '512 MB'."""
33
+ if isinstance(memory, (int, float)):
34
+ return float(memory)
35
+ m = re.fullmatch(r'\s*([0-9.]+)\s*([kmgt]?i?b?)\s*', str(memory).lower())
36
+ if m is None:
37
+ raise ValueError(f"cannot parse memory size {memory!r}, use e.g. '4GB'")
38
+ unit = m.group(2).rstrip('b').rstrip('i')
39
+ return float(m.group(1)) * 1024 ** ' kmgt'.index(unit or ' ')
40
+
41
+
42
+ #: default memory budget of one worker process, used to cap the number of
43
+ #: workers of parallel computations when ``memory_limit='auto'``
44
+ WORKER_MEMORY_DEFAULT = '2GB'
45
+
46
+
47
+ def _n_parallel_workers(parallel, n_tasks, memory_limit='auto'):
48
+ """
49
+ Number of worker processes used to run ``n_tasks`` independent tasks.
50
+
51
+ Parameters
52
+ ----------
53
+ parallel : bool, int or str
54
+ False (or 0, 1): no parallelization. An int: maximum number of workers.
55
+ 'max' or 'max-1': all CPUs, or all CPUs but one.
56
+ n_tasks : int
57
+ Number of tasks, more workers than tasks would be idle.
58
+ memory_limit : str or float, 'auto'
59
+ Memory needed by one worker, as bytes or a string like '4GB'. The
60
+ number of workers is capped so that they fit in the available memory.
61
+ 'auto' (or the legacy 'max') uses ``WORKER_MEMORY_DEFAULT``, None
62
+ disables the cap.
63
+
64
+ Returns
65
+ -------
66
+ n_workers : int
67
+ Number of workers, 1 meaning sequential computation.
68
+ """
69
+ if parallel is False or parallel is None:
70
+ return 1
71
+ nb_cores = cpu_count()
72
+ if parallel is True or parallel == 'max':
73
+ n = nb_cores
74
+ elif parallel == 'max-1':
75
+ n = nb_cores - 1
76
+ elif isinstance(parallel, (int, np.integer)):
77
+ n = min(int(parallel), nb_cores)
78
+ else:
79
+ raise ValueError(f"`parallel` must be a bool, an int, 'max' or 'max-1', got {parallel!r}")
80
+ n = min(n, n_tasks)
81
+ if memory_limit is not None and n > 1:
82
+ if memory_limit in ('auto', 'max'):
83
+ memory_limit = WORKER_MEMORY_DEFAULT
84
+ available = _available_memory()
85
+ if available is not None:
86
+ n = min(n, int(0.9 * available // _parse_memory(memory_limit)))
87
+ return max(1, n)
88
+
89
+
90
+ def _parallel_map(func, tasks, n_workers, desc=None, verbose=0, total=None):
91
+ """
92
+ Return ``[func(*args) for args in tasks]``, computed by ``n_workers`` processes.
93
+
94
+ ``tasks`` yields tuples of positional arguments. It can be a generator: it
95
+ is consumed lazily, so tasks' data is only created a few tasks ahead of
96
+ the workers.
97
+
98
+ Workers are joblib's loky processes: unlike dask's or multiprocessing's
99
+ spawned workers they don't re-execute the calling script, so scripts don't
100
+ need an ``if __name__ == '__main__':`` guard, results are collected
101
+ directly by the calling process, and the number of BLAS / OpenMP threads
102
+ of each worker is limited to avoid over-subscription.
103
+ """
104
+ if verbose > 0:
105
+ tasks = tqdm(tasks, desc=desc, total=total)
106
+ if n_workers <= 1:
107
+ return [func(*args) for args in tasks]
108
+ return Parallel(n_jobs=n_workers, backend='loky')(delayed(func)(*args) for args in tasks)
109
+
110
+
111
+ def _call_with_kwarg(func, key, value):
112
+ """``func(**{key: value})``, to map a partial function over a keyword argument."""
113
+ return func(**{key: value})
mosna/_settings.py ADDED
@@ -0,0 +1,33 @@
1
+ """
2
+ Package-level settings, read and set on the ``mosna`` namespace but stored
3
+ in the submodule that uses them, so that ``mosna.gpu_clustering = False``
4
+ reaches the clustering code.
5
+ """
6
+
7
+ import importlib
8
+ import types
9
+
10
+ #: setting name -> submodule holding it
11
+ SETTINGS = {
12
+ 'gpu_clustering': '_gpu',
13
+ 'WORKER_MEMORY_DEFAULT': '_parallel',
14
+ }
15
+
16
+
17
+ def _home(name):
18
+ return importlib.import_module(f'mosna.{SETTINGS[name]}')
19
+
20
+
21
+ class SettingsModule(types.ModuleType):
22
+ """Module type forwarding the settings to the submodules holding them."""
23
+
24
+ def __getattr__(self, name):
25
+ if name in SETTINGS:
26
+ return getattr(_home(name), name)
27
+ raise AttributeError(f"module {self.__name__!r} has no attribute {name!r}")
28
+
29
+ def __setattr__(self, name, value):
30
+ if name in SETTINGS:
31
+ setattr(_home(name), name, value)
32
+ else:
33
+ super().__setattr__(name, value)
mosna/_utils.py ADDED
@@ -0,0 +1,47 @@
1
+ """
2
+ Small array helpers shared by several modules.
3
+ """
4
+
5
+ import functools
6
+ import sys
7
+ import warnings
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+
13
+ def ignore_warnings(*categories):
14
+ """
15
+ Decorator ignoring warnings of the given categories while the decorated
16
+ function runs, without changing the warnings filters of the caller.
17
+ """
18
+
19
+ def decorator(func):
20
+ @functools.wraps(func)
21
+ def wrapper(*args, **kwargs):
22
+ with warnings.catch_warnings():
23
+ for category in categories:
24
+ warnings.simplefilter('ignore', category)
25
+ return func(*args, **kwargs)
26
+
27
+ return wrapper
28
+
29
+ return decorator
30
+
31
+
32
+ def to_numpy(data):
33
+ if isinstance(data, (pd.DataFrame, pd.Series)):
34
+ data = data.values.ravel()
35
+ # data can only be a cupy array if cupy has been imported
36
+ cp = sys.modules.get('cupy')
37
+ if cp is not None and isinstance(data, cp.ndarray):
38
+ data = cp.asnumpy(data)
39
+ return data
40
+
41
+
42
+ def renormalize(data, mini, maxi):
43
+ data = data - np.min(data)
44
+ data = data / np.max(data)
45
+ data = data * (maxi - mini)
46
+ data = data + mini
47
+ return data